Summary of Four Ways for JAVA to Send HTTP Requests

  • 2021-09-05 00:03:44
  • OfStack

Source code: http://github.com/lovewenyo/HttpDemo

1. HttpURLConnection

Use the net provided natively by JDK without the need for other jar packages;

HttpURLConnection is a subclass of URLConnection, which provides more methods and is more convenient to use.


package httpURLConnection;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionHelper {

 public static String sendRequest(String urlParam,String requestType) {

  HttpURLConnection con = null; 

  BufferedReader buffer = null; 
  StringBuffer resultBuffer = null; 

  try {
   URL url = new URL(urlParam); 
   // Get the connection object 
   con = (HttpURLConnection) url.openConnection(); 
   // Set the request type 
   con.setRequestMethod(requestType); 
   // Set the data type and character set type to be returned by the request 
   con.setRequestProperty("Content-Type", "application/json;charset=GBK"); 
   // Allow to write 
   con.setDoOutput(true);
   // Allow reading 
   con.setDoInput(true);
   // Do not use caching 
   con.setUseCaches(false);
   // Get the response code 
   int responseCode = con.getResponseCode();

   if(responseCode == HttpURLConnection.HTTP_OK){
    // Get the response flow 
    InputStream inputStream = con.getInputStream();
    // Convert a response stream to a string 
    resultBuffer = new StringBuffer();
    String line;
    buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
    while ((line = buffer.readLine()) != null) {
     resultBuffer.append(line);
    }
    return resultBuffer.toString();
   }

  }catch(Exception e) {
   e.printStackTrace();
  }
  return "";
 }
 public static void main(String[] args) {

  String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
  System.out.println(sendRequest(url,"POST"));
 }
}

2. URLConnection

Use net provided native to JDK without other jar packages;

HttpURLConnection is recommended


package uRLConnection;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionHelper {

 public static String sendRequest(String urlParam) {

  URLConnection con = null; 

  BufferedReader buffer = null; 
  StringBuffer resultBuffer = null; 

  try {
    URL url = new URL(urlParam); 
    con = url.openConnection(); 

   // Set the data type and character set type to be returned by the request 
   con.setRequestProperty("Content-Type", "application/json;charset=GBK"); 
   // Allow to write 
   con.setDoOutput(true);
   // Allow reading 
   con.setDoInput(true);
   // Do not use caching 
   con.setUseCaches(false);
   // Get the response flow 
   InputStream inputStream = con.getInputStream();
   // Convert a response stream to a string 
   resultBuffer = new StringBuffer();
   String line;
   buffer = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
   while ((line = buffer.readLine()) != null) {
    resultBuffer.append(line);
   }
   return resultBuffer.toString();

  }catch(Exception e) {
   e.printStackTrace();
  }

  return "";
 }
 public static void main(String[] args) {
  String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
  System.out.println(sendRequest(url));
 }
}

3. HttpClient

Easy to use, I personally prefer this method, but rely on the third-party jar package, and the related maven dependencies are as follows:


<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
 <groupId>commons-httpclient</groupId>
 <artifactId>commons-httpclient</artifactId>
 <version>3.1</version>
</dependency

package httpClient;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientHelper {
 public static String sendPost(String urlParam) throws HttpException, IOException {
  //  Create httpClient Instance object 
  HttpClient httpClient = new HttpClient();
  //  Settings httpClient Timeout to connect to host server: 15000 Milliseconds 
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
  //  Create post Request method instance object 
  PostMethod postMethod = new PostMethod(urlParam);
  //  Settings post Request timeout 
  postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
  postMethod.addRequestHeader("Content-Type", "application/json");

  httpClient.executeMethod(postMethod);

  String result = postMethod.getResponseBodyAsString();
  postMethod.releaseConnection();
  return result;
 }
 public static String sendGet(String urlParam) throws HttpException, IOException {
  //  Create httpClient Instance object 
  HttpClient httpClient = new HttpClient();
  //  Settings httpClient Timeout to connect to host server: 15000 Milliseconds 
  httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
  //  Create GET Request method instance object 
  GetMethod getMethod = new GetMethod(urlParam);
  //  Settings post Request timeout 
  getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
  getMethod.addRequestHeader("Content-Type", "application/json");

  httpClient.executeMethod(getMethod);

  String result = getMethod.getResponseBodyAsString();
  getMethod.releaseConnection();
  return result;
 }
 public static void main(String[] args) throws HttpException, IOException {
  String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
  System.out.println(sendPost(url));
  System.out.println(sendGet(url));
 }
}

4. Socket

Use the net provided natively by JDK without other jar packages;

It's a little troublesome to use.


package socket;
import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.Socket; 
import java.net.URLEncoder; 

import javax.net.ssl.SSLSocket; 
import javax.net.ssl.SSLSocketFactory; 

public class SocketForHttpTest { 

 private int port; 
 private String host; 
 private Socket socket; 
 private BufferedReader bufferedReader; 
 private BufferedWriter bufferedWriter; 

 public SocketForHttpTest(String host,int port) throws Exception{ 

  this.host = host; 
  this.port = port; 

  /** 
   * http Agreement  
   */ 
  // socket = new Socket(this.host, this.port); 

  /** 
   * https Agreement  
   */ 
  socket = (SSLSocket)((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(this.host, this.port); 


 } 

 public void sendGet() throws IOException{ 
  //String requestUrlPath = "/z69183787/article/details/17580325"; 
  String requestUrlPath = "/";   

  OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream()); 
  bufferedWriter = new BufferedWriter(streamWriter);    
  bufferedWriter.write("GET " + requestUrlPath + " HTTP/1.1\r\n"); 
  bufferedWriter.write("Host: " + this.host + "\r\n"); 
  bufferedWriter.write("\r\n"); 
  bufferedWriter.flush(); 

  BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream()); 
  bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8")); 
  String line = null; 
  while((line = bufferedReader.readLine())!= null){ 
   System.out.println(line); 
  } 
  bufferedReader.close(); 
  bufferedWriter.close(); 
  socket.close(); 

 } 


 public void sendPost() throws IOException{ 
   String path = "/"; 
   String data = URLEncoder.encode("name", "utf-8") + "=" + URLEncoder.encode(" Zhang 3", "utf-8") + "&" + 
      URLEncoder.encode("age", "utf-8") + "=" + URLEncoder.encode("32", "utf-8"); 
   // String data = "name=zhigang_jia"; 
   System.out.println(">>>>>>>>>>>>>>>>>>>>>"+data);    
   OutputStreamWriter streamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8"); 
   bufferedWriter = new BufferedWriter(streamWriter);     
   bufferedWriter.write("POST " + path + " HTTP/1.1\r\n"); 
   bufferedWriter.write("Host: " + this.host + "\r\n"); 
   bufferedWriter.write("Content-Length: " + data.length() + "\r\n"); 
   bufferedWriter.write("Content-Type: application/x-www-form-urlencoded\r\n"); 
   bufferedWriter.write("\r\n"); 
   bufferedWriter.write(data); 

   bufferedWriter.write("\r\n"); 
   bufferedWriter.flush(); 

   BufferedInputStream streamReader = new BufferedInputStream(socket.getInputStream()); 
   bufferedReader = new BufferedReader(new InputStreamReader(streamReader, "utf-8")); 
   String line = null; 
   while((line = bufferedReader.readLine())!= null) 
   { 
    System.out.println(line); 
   } 
   bufferedReader.close(); 
   bufferedWriter.close(); 
   socket.close(); 
 } 

 public static void main(String[] args) throws Exception { 
  /** 
   * http Protocol testing  
   */ 
  //SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 80); 
  /** 
   * https Protocol testing  
   */ 
  SocketForHttpTest forHttpTest = new SocketForHttpTest("www.baidu.com", 443); 
  try { 
   forHttpTest.sendGet(); 
  // forHttpTest.sendPost(); 
  } catch (IOException e) { 

   e.printStackTrace(); 
  } 
 } 

} 

Summarize


Related articles: