使用JAVA实现http通信详解

网友投稿 185 2023-07-29


使用JAVA实现http通信详解

Http通信概述

Http通信主要有两种方式POST方式和GET方式。前者通过Http消息实体发送数据给服务器,安全性高,数据传输大小没有限制,后者通过URL的查询字符串传递给服务器参数,以明文显示在浏览器地址栏,保密性差,最多传输2048个字符。但是GET请求并不是一无是处——GET请求大多用于查询(读取资源),效率高。POST请求用于注册、登录等安全性较高且向数据库中写入数据的操作。

除了POST和GET,http通信还有其他方式!请参见http请求的方法

编码前的准备

在进行编码之前,我们先创建一个Servlet,该Servlet接收客户端的参数(name和age),并响应客户端。

@WebServlet(urlPatterns={"/demo.do"})

public class DemoServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

String name = request.getParameter("name");

String age = request.getParameter("age");

PrintWriter pw = response.getWriter();

pw.print("您使用GET方式请求该Servlet。
" + "name = " + name + ",age = " + age);

pw.flush();

pw.close();

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

String name = request.getParameter("name");

String age = request.getParameter("age");

PrintWriter pw = response.getWriter();

pw.print("您使用POST方式请求该Servlet。
" + "name = " + name + ",age = " + age);

pw.flush();

pw.close();

}

}

使用JDK实现http通信

使用URLConnection实现GET请求

实例化一个java.net.URL对象;

通过URL对象的openConnection()方法得到一个java.net.URLConnection;

通过URLConnection对象的getInputStream()方法获得输入流;

读取输入流;

关闭资源。

public void get() throws Exception{

URL url = new URL("http://127.0.0.1/http/demo.do?name=Jack&age=10");

URLConnection urlConnection = url.openConnection(); // 打开连接

BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8")); // 获取输入流

String line = null;

StringBuilder sb = new StringBuilder();

while ((line = br.readLine()) != null) {

sb.append(line + "\n");

}

System.out.println(sb.toString());

}

使用HttpURLConnection实现POST请求

java.net.HttpURLConnection是java.net.URL的子类,提供了更多的关于http的操作(getXXX 和 setXXX方法)。该类中定义了一系列的HTTP状态码:

public void post() throws IOException{

URL url = new URL("http://127.0.0.1/http/demo.do");

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnectiZDExaWon();

httpURLConnection.setDoInput(true);

httpURLConnection.setDoOutput(true); // 设置该连接是可以输出的

httpURLConnection.setRequestMethod("POST"); // 设置请求方式

httpURLConnection.setRequestProperty("charset", "utf-8");

PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));

pw.write("name=welcome"); // 向连接中输出数据(相当于发送数据给服务器)

pw.write("&age=14");

pw.flush();

pw.close();

BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));

String line = null;

StringBuilder sb = new StringBuilder();

while ((line = br.readLine()) != null) { // 读取数据

sb.append(line + "\n");

}

System.out.println(sb.toString());

}

使用httpclient进行http通信

httpclient大大简化了JDK中http通信的实现。

maven依赖:

org.apache.httpcomponents

httpclient

4.3.6

GET请求

public void httpclientGet() throws Exception{

// 创建HttpClient对象

HttpClient client = HttpClients.createDefault();

// 创建GET请求(在构造器中传入URL字符串即可)

HttpGet get = new HttpGet("http://127.0.0.1/http/demo.do?name=admin&age=40");

// 调用HttpClient对象的execute方法获得响应

HttpResponse response = client.execute(get);

// 调用HttpResponse对象的getEntity方法得到响应实体

HttpEntity httpEntity = response.getEntity();

// 使用EntityUtils工具类得到响应的字符串表示

String result = EntityUtils.toString(httpEntity,"utf-8");

System.out.println(result);

}

POST请求

public void httpclientPost() throws Exception{

// 创建HttpClient对象

HttpClient client = HttpClients.createDefault();

// 创建POST请求

HttpPost post = new HttpPost("http://127.0.0.1/http/demo.http://do");

// 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值)

List parameters = new ArrayList<>();

parameters.add(new BasicNameValuePair("name", "张三"));

parameters.add(new BasicNameValuePair("age", "25"));

// 向POST请求中添加消息实体

post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));

// 得到响应并转化成字符串

HttpResponse response = client.execute(post);

HttpEntity httpEntity = response.getEntity();

String result = EntityUtils.toString(httpEntity,"utf-8");

System.out.println(result);

}

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Android应用开发之将SQLite和APK一起打包的方法
下一篇:innerHTML中标签可以换行的方法汇总
相关文章

 发表评论

暂时没有评论,来抢沙发吧~