Using Java to implement HTTP communication

Source: Internet
Author: User

HTTP Communication overview

There are two main ways in which HTTP communication is post and get. The former through the HTTP message entity sends the data to the server, the security is high, the data transmission size is not limited, the latter passes the URL query string to the server parameter, in clear text displays in the browser address bar, the confidentiality is poor, transmits up to 2048 characters. But get requests are not useless.--get requests are mostly used for querying (reading resources) and are highly efficient. Post requests are used to register, log in, and so on, and to write data to the database.

There are other ways besides post and get,http communication! See methods for HTTP requests

Pre-coding preparation

Before encoding, we create a servlet that receives the client's parameters (name and age) and responds to the client.

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

Using the JDK for HTTP communication

Implementing a GET request with URLConnection

Instantiate a Java.net.URL object;
A java.net.URLConnection is obtained by the OpenConnection () method of the URL object;
The input stream is obtained through the getInputStream () method of the URLConnection object.
Read input stream;
Close the resource.

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

Implementing a POST request using HttpURLConnection

Java.net.HttpURLConnection is a subclass of Java.net.URL that provides more operations on HTTP (GetXXX and Setxxx methods). A series of HTTP status codes are defined in this class:

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

Using HttpClient for HTTP communication

HttpClient greatly simplifies the implementation of HTTP communication in the JDK.

Maven dependencies:

?
12345 <dependency>  <groupId>org.apache.httpcomponents</groupId>  <artifactId>httpclient</artifactId>  <version>4.3.6</version></dependency>

GET request

?
123456789101112131415161718 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 request

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

HttpClient is a sub-project under Apache Jakarta common to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol. HttpClient has been used in many projects, such as the two other open source projects that are famous on Apache Jakarta Cactus and Htmlunit use httpclient.

Using Java to implement HTTP communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.