Detailed explanation of three ways for java to realize HTTP request

  • 2021-07-22 09:52:03
  • OfStack

At present, JAVA has two methods to implement HTTP requests: One is implemented through HTTPClient, a third-party open source framework. HTTPClient has a good encapsulation of HTTP, which can basically meet most of our needs. HttpClient3.1 is a toolkit for operating remote url under org. apache. commons. httpclient. Although it is no longer updated, there are still many codes using httpClient3.1 in the implementation work. HttpClient4.5 is a toolkit for operating remote url under org. apache. http. client. The other one is implemented by HttpURLConnection, and HttpURLConnection is a standard class of JAVA, which is a native implementation of JAVA.

I have used three ways in my work. I will share it with you after summarizing 1, which is also convenient for me to use later. I don't say much about the code.

Mode 1: java native HttpURLConnection


package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
  public static String doGet(String httpurl) {
    HttpURLConnection connection = null;
    InputStream is = null;
    BufferedReader br = null;
    String result = null;//  Returns the result string 
    try {
      //  Create remote url Connection object 
      URL url = new URL(httpurl);
      //  By remote url Connection object open 1 A connection, strong conversion into httpURLConnection Class 
      connection = (HttpURLConnection) url.openConnection();
      //  Set the connection mode: get
      connection.setRequestMethod("GET");
      //  Set the timeout for connecting to the host server: 15000 Milliseconds 
      connection.setConnectTimeout(15000);
      //  Set the time to read remotely returned data: 60000 Milliseconds 
      connection.setReadTimeout(60000);
      //  Send a request 
      connection.connect();
      //  Pass connection Connect to get the input stream 
      if (connection.getResponseCode() == 200) {
        is = connection.getInputStream();
        //  Encapsulate the input stream is And specify the character set 
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        //  Store data 
        StringBuffer sbf = new StringBuffer();
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //  Close resources 
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      connection.disconnect();//  Close remote connection 
    }

    return result;
  }

  public static String doPost(String httpUrl, String param) {

    HttpURLConnection connection = null;
    InputStream is = null;
    OutputStream os = null;
    BufferedReader br = null;
    String result = null;
    try {
      URL url = new URL(httpUrl);
      //  By remote url Connection object opens a connection 
      connection = (HttpURLConnection) url.openConnection();
      //  Set the connection request method 
      connection.setRequestMethod("POST");
      //  Set the time-out for connecting to the host server: 15000 Milliseconds 
      connection.setConnectTimeout(15000);
      //  Set the timeout for reading data returned by the host server: 60000 Milliseconds 
      connection.setReadTimeout(60000);

      //  The default value is: false When transferring data to a remote server, / When writing data, you need to set to true
      connection.setDoOutput(true);
      //  The default value is: true When data is currently being read from the remote service, set to true This parameter is optional 
      connection.setDoInput(true);
      //  Formatting incoming parameters : The request parameter should be  name1=value1&name2=value2  The form of. 
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      //  Set authentication information: Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
      connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      //  Obtain through the connection object 1 Output streams 
      os = connection.getOutputStream();
      //  Write out the parameters through the output stream object / Transmit out , It is written through an array of bytes 
      os.write(param.getBytes());
      //  Obtain through the connection object 1 Input streams to read remotely 
      if (connection.getResponseCode() == 200) {

        is = connection.getInputStream();
        //  Wrapping an input stream object :charset Set according to the requirements of the work item group 
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        String temp = null;
        //  Cyclic traversal 1 Row 1 Row read data 
        while ((temp = br.readLine()) != null) {
          sbf.append(temp);
          sbf.append("\r\n");
        }
        result = sbf.toString();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //  Close resources 
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != os) {
        try {
          os.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      //  Disconnect from remote address url Connection of 
      connection.disconnect();
    }
    return result;
  }
}

Mode 2: apache HttpClient3.1


package com.powerX.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClient3 {

  public static String doGet(String url) {
    // 输入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 创建httpClient实例
    HttpClient httpClient = new HttpClient();
    // 设置http连接主机服务超时时间:15000毫秒
    // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建1个Get方法实例对象
    GetMethod getMethod = new GetMethod(url);
    // 设置get请求超时为60000毫秒
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
    try {
      // 执行Get方法
      int statusCode = httpClient.executeMethod(getMethod);
      // 判断返回码
      if (statusCode != HttpStatus.SC_OK) {
        // 如果状态码返回的不是ok,说明失败了,打印错误信息
        System.err.println("Method faild: " + getMethod.getStatusLine());
      } else {
        // 通过getMethod实例,获取远程的1个输入流
        is = getMethod.getResponseBodyAsStream();
        // 包装输入流
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        StringBuffer sbf = new StringBuffer();
        // 读取封装的输入流
        String temp = null;
        while ((temp = br.readLine()) != null) {
          sbf.append(temp).append("\r\n");
        }

        result = sbf.toString();
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 释放连接
      getMethod.releaseConnection();
    }
    return result;
  }

  public static String doPost(String url, Map<String, Object> paramMap) {
    // 获取输入流
    InputStream is = null;
    BufferedReader br = null;
    String result = null;
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建post请求方法实例对象
    PostMethod postMethod = new PostMethod(url);
    // 设置post请求超时时间
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

    NameValuePair[] nvp = null;
    // 判断参数map集合paramMap是否为空
    if (null != paramMap && paramMap.size() > 0) {// 不为空
      // 创建键值参数对象数组,大小为参数的个数
      nvp = new NameValuePair[paramMap.size()];
      // 循环遍历参数集合map
      Set<Entry<String, Object>> entrySet = paramMap.entrySet();
      // 获取迭代器
      Iterator<Entry<String, Object>> iterator = entrySet.iterator();

      int index = 0;
      while (iterator.hasNext()) {
        Entry<String, Object> mapEntry = iterator.next();
        // 从mapEntry中获取key和value创建键值对象存放到数组中
        try {
          nvp[index] = new NameValuePair(mapEntry.getKey(),
              new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        index++;
      }
    }
    // 判断nvp数组是否为空
    if (null != nvp && nvp.length > 0) {
      // 将参数存放到requestBody对象中
      postMethod.setRequestBody(nvp);
    }
    // 执行POST方法
    try {
      int statusCode = httpClient.executeMethod(postMethod);
      // 判断是否成功
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method faild: " + postMethod.getStatusLine());
      }
      // 获取远程返回的数据
      is = postMethod.getResponseBodyAsStream();
      // 封装输入流
      br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

      StringBuffer sbf = new StringBuffer();
      String temp = null;
      while ((temp = br.readLine()) != null) {
        sbf.append(temp).append("\r\n");
      }

      result = sbf.toString();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 关闭资源
      if (null != br) {
        try {
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != is) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      // 释放连接
      postMethod.releaseConnection();
    }
    return result;
  }
}

Mode 3: apache httpClient 4.5


package com.powerX.httpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient4 {

  public static String doGet(String url) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String result = "";
    try {
      //  Created by address default configuration 1 A httpClient Instances 
      httpClient = HttpClients.createDefault();
      //  Create httpGet Remote connection instance 
      HttpGet httpGet = new HttpGet(url);
      //  Set the request header information and authenticate 
      httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
      //  Setting configuration request parameters 
      RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)//  Connecting to host service timeout 
          .setConnectionRequestTimeout(35000)//  Request timeout 
          .setSocketTimeout(60000)//  Data read timeout 
          .build();
      //  For httpGet Instance Setting Configuration 
      httpGet.setConfig(requestConfig);
      //  Execute get Request to get the return object 
      response = httpClient.execute(httpGet);
      //  Get the return data through the return object 
      HttpEntity entity = response.getEntity();
      //  Pass EntityUtils In toString Method converts the result to a string 
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //  Close resources 
      if (null != response) {
        try {
          response.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != httpClient) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }

  public static String doPost(String url, Map<String, Object> paramMap) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    String result = "";
    //  Create httpClient Instances 
    httpClient = HttpClients.createDefault();
    //  Create httpPost Remote connection instance 
    HttpPost httpPost = new HttpPost(url);
    //  Configure request parameter instance 
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)//  Set the connection host service timeout 
        .setConnectionRequestTimeout(35000)//  Set the connection request timeout 
        .setSocketTimeout(60000)//  Set the read data connection timeout 
        .build();
    //  For httpPost Instance Setting Configuration 
    httpPost.setConfig(requestConfig);
    //  Set the request header 
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    //  Encapsulation post Request parameter 
    if (null != paramMap && paramMap.size() > 0) {
      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      //  Pass map Integration entrySet Method gets entity
      Set<Entry<String, Object>> entrySet = paramMap.entrySet();
      //  Loop through to get iterators 
      Iterator<Entry<String, Object>> iterator = entrySet.iterator();
      while (iterator.hasNext()) {
        Entry<String, Object> mapEntry = iterator.next();
        nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
      }

      //  For httpPost Set the encapsulated request parameters 
      try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    try {
      // httpClient Object execution post Request , And returns the response parameter object 
      httpResponse = httpClient.execute(httpPost);
      //  Get the response content from the response object 
      HttpEntity entity = httpResponse.getEntity();
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //  Close resources 
      if (null != httpResponse) {
        try {
          httpResponse.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (null != httpClient) {
        try {
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }
}

Sometimes when we use post request, the parameters may be passed in json or other formats. At this time, we need to change the setting information of the request header and parameters. Take httpClient4.5 as an example, change the following two columns: httpPost. setEntity (new StringEntity ("Your json String")); httpPost. addHeader ("Content-Type", "application/json").


Related articles: