[Turn] Java simulate http request, call external interfaces api (a): The difference between the HttpURLConnection and HttpClient

  In JAVA, and org.apache.http.client.HttpClient java.net.HttpURLConnection The two classes, can be an analog implementation of HTTP requests.

  Wherein, the HttpURLConnection jdk is to provide a class which implements all operations http requests, but because of its method of operation biased toward atoms, and therefore, the HttpURLConnection http request for simple, complex and troublesome to achieve http request. HttpClient class and, is made further HttpURLConnection package, especially for complex http requests made to achieve a good optimization.

Reprinted Note: The following text content reproduced from "China fishing boat" 
Disclaimer: This article is the original article CSDN bloggers "China fishing boat", following the CC 4.0 by- SA copyright agreement, reproduced, please attach the original source link and this statement. 
Original link: HTTPS: // blog.csdn.net/amosjob/article/details/82782546

Start --------- ------- text

A, HttpURLConnection objects

  1. HttpURLConnection objects needs to be obtained by the openConnection () method of class URL, it can not be directly constructed.

HttpsURLConnection urlconn = null;
URL url = new URL(address);
urlconn = (HttpsURLConnection)url.openConnection();

  2. HttpURLConnection the connect () function, but actually set up a TCP connection with the server, and sends an HTTP request is not practical. HTTP requests until we actually get the server response data (such as call getInputStream (), getResponseCode () method, etc.) when the official sent. And configured HttpURLConnection objects are required to complete before the connect () method is executed.

urlconn = (HttpsURLConnection)url.openConnection();
urlconn.setRequestMethod("GET");
urlconn.setConnectTimeout(5000);
urlconn.setReadTimeout(5000);
urlconn.setUseCaches(false);
urlconn.connect();

  3. HttpURLConnection is based on HTTP protocol, which is implemented by the underlying socket communication. If you do not set a timeout (timeout), under abnormal network conditions, it may cause the program not to continue down the dead.

public HttpURLConnection(URL url, String s, int i){
this(url, new Proxy(java.net.Proxy.Type.HTTP, 
InetSocketAddress.createUnresolved(s, i)));
}

  4. content through HTTP body OutputStream stream writing, the data written to the stream does not immediately sent to the network, but in the buffer memory, when current shutdown to be generated based on the content written HTTP body .

  5. When the getInputStream call () method returns an input stream for HTTP server to return the requested information read from.

InputStream inputStream = urlconn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader buff = new BufferedReader(inputStreamReader);
String line = buff.readLine();
while(line != null){
System.out.println(line);
line = buff.readLine();
}
inputStream.close();
inputStreamReader.close();
buff.close();

  6. We can use HttpURLConnection.connect () method of manually sending a HTTP request, but if you want to get the HTTP response when the request is automatically initiated, for example, we use HttpURLConnection.getInputStream () method of the time, so there is no need call connect () method.

 

Two, HttpClient objects

  HttpClient is simplified compared to the object processing HttpURLConnection Session, Cookie's.

  It can be said HttpClient is an enhanced version of the HttpURLConnection, HttpClient can do HttpURLConnection all objects can do.

  Open source Apache HttpClient is provided it is a simple HTTP client, not the browser is configured to send HTTP requests, receives HTTP response. But the response from the server will not be cached. It just focus on how the transmission request, receiving a response, and manage HTTP connections.

 

HttpClient use

Use HttpClient transmission request, receiving a response is very simple, as long as the following steps.

  1. 创建HttpClient对象,CloseableHttpClient httpclient = HttpClients.createDefault();

  2. If you need to send a GET request, create HttpGet objects; if you need to send a POST request to create HttpPost object.

  3. If transmit request parameters, can be called HttpGet, HttpPost common the setHeader () method or the addHeader () method to add a request parameter; for HttpPost object can call setEntity (Method set request parameters.

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
httpPost.setEntity(entity);

  4. Call HttpClient object execute (HttpUriRequest request) transmission request, performing the method returns a HttpResponse.

  5. Call the HttpResponse getAllHeaders (), getHeaders (String name) or the like can be obtained in response to the first server; the call HttpResponse getEntity () method gets HttpEntity object content server in response to the package. Program available through the content server in response to the object.

Text END --------- -------

Third, the recommended reading

  1. HttpClient and the difference HttpURLConnection
  2. HttpClient and HttpURLConnection of use and differences
  3. HTTPClient implement GET / POST request Examples
  4. HTTPClent for binary data upload examples
  5. HTTPURLConnection implement GET / POST request Examples

 

Guess you like

Origin www.cnblogs.com/newbie27/p/11404365.html