欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用JAVA实现http通信详解

程序员文章站 2024-03-05 15:05:06
http通信概述 http通信主要有两种方式post方式和get方式。前者通过http消息实体发送数据给服务器,安全性高,数据传输大小没有限制,后者通过url的查询字符串...

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。<br />" + "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。<br />" + "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());
}

使用JAVA实现http通信详解

使用httpurlconnection实现post请求

java.net.httpurlconnection是java.net.url的子类,提供了更多的关于http的操作(getxxx 和 setxxx方法)。该类中定义了一系列的http状态码:

使用JAVA实现http通信详解 

public void post() throws ioexception{

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

  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());
}

使用JAVA实现http通信详解

使用httpclient进行http通信

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

maven依赖:

<dependency>
  <groupid>org.apache.httpcomponents</groupid>
  <artifactid>httpclient</artifactid>
  <version>4.3.6</version>
</dependency>

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);
}

使用JAVA实现http通信详解

post请求

public void httpclientpost() throws exception{

  // 创建httpclient对象
  httpclient client = httpclients.createdefault();

  // 创建post请求
  httppost post = new httppost("http://127.0.0.1/http/demo.do");

  // 创建一个list容器,用于存放基本键值对(基本键值对即:参数名-参数值)
  list<basicnamevaluepair> 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);
}

使用JAVA实现http通信详解

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