SoFunction
Updated on 2025-04-04

Several common types of sending http request instances in java

Several common types of java sending http request instances

<span style="font-family: Arial, Helvetica, sans-serif;">import ;</span>
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
/**
  * @Description: Send http request help class
  * @author:liuyc
  * @time: May 17, 2016 at 3:25:32 pm
  */
public class HttpClientHelper {
	/**
	  * @Description: Send post request using HttpURLConnection
	  * @author:liuyc
	  * @time: May 17, 2016 at 3:26:07 pm
	  */
	public static String sendPost(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		StringBuffer resultBuffer = null;
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; e : ()) {
				(());
				("=");
				(());
				("&amp;");
			}
		}
		HttpURLConnection con = null;
		OutputStreamWriter osw = null;
		BufferedReader br = null;
		// Send a request		try {
			URL url = new URL(urlParam);
			con = (HttpURLConnection) ();
			("POST");
			(true);
			(true);
			(false);
			("Content-Type", "application/x-www-form-urlencoded");
			if (sbParams != null &amp;&amp; () &gt; 0) {
				osw = new OutputStreamWriter((), charset);
				((0, () - 1));
				();
			}
			// Read the return content			resultBuffer = new StringBuffer();
			int contentLength = (("Content-Length"));
			if (contentLength &gt; 0) {
				br = new BufferedReader(new InputStreamReader((), charset));
				String temp;
				while ((temp = ()) != null) {
					(temp);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (osw != null) {
				try {
					();
				} catch (IOException e) {
					osw = null;
					throw new RuntimeException(e);
				} finally {
					if (con != null) {
						();
						con = null;
					}
				}
			}
			if (br != null) {
				try {
					();
				} catch (IOException e) {
					br = null;
					throw new RuntimeException(e);
				} finally {
					if (con != null) {
						();
						con = null;
					}
				}
			}
		}
 
		return ();
	}
 
	/**
	  * @Description: Use URLConnection to send post
	  * @author:liuyc
	  * @time: May 17, 2016 at 3:26:52 pm
	  */
	public static String sendPost2(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		StringBuffer resultBuffer = null;
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; e : ()) {
				(());
				("=");
				(());
				("&amp;");
			}
		}
		URLConnection con = null;
		OutputStreamWriter osw = null;
		BufferedReader br = null;
		try {
			URL realUrl = new URL(urlParam);
			// Open the connection to the URL			con = ();
			// Set common request attributes			("accept", "*/*");
			 ("connection", "Keep-Alive");
			 ("Content-Type", "application/x-www-form-urlencoded");
			 ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			 // The following two lines must be set to send a POST request
			 (true);
			 (true);
			 // Get the output stream corresponding to the URLConnection object
			 osw = new OutputStreamWriter((), charset);
			 if (sbParams != null && () > 0) {
				 // Send request parameters
				 ((0, () - 1));
				 // Buffer of flush output stream
				 ();
			 }
			 // Define the BufferedReader input stream to read the URL response
			 resultBuffer = new StringBuffer();
			 int contentLength = (("Content-Length"));
			 if (contentLength > 0) {
				 br = new BufferedReader(new InputStreamReader((), charset));
				 String temp;
				 while ((temp = ()) != null) {
					 (temp);
				 }
			 }
		 } catch (Exception e) {
			 throw new RuntimeException(e);
		 } finally {
			 if (osw != null) {
				 try {
					 ();
				 } catch (IOException e) {
					 osw = null;
					 throw new RuntimeException(e);
				 }
			 }
			 if (br != null) {
				 try {
					 ();
				 } catch (IOException e) {
					 br = null;
					 throw new RuntimeException(e);
				 }
			 }
		 }
		 return ();
	 }
 
	 /**
	  * @Description: Send get request to save download file
	  * @author:liuyc
	  * @time: May 17, 2016 at 3:27:29 pm
	  */
	public static void sendGetAndSaveFile(String urlParam, Map&lt;String, Object&gt; params, String fileSavePath) {
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; entry : ()) {
				(());
				("=");
				(());
				("&amp;");
			}
		}
		HttpURLConnection con = null;
		BufferedReader br = null;
		FileOutputStream os = null;
		try {
			URL url = null;
			if (sbParams != null &amp;&amp; () &gt; 0) {
				url = new URL(urlParam + "?" + (0, () - 1));
			} else {
				url = new URL(urlParam);
			}
			con = (HttpURLConnection) ();
			("Content-Type", "application/x-www-form-urlencoded");
			();
			InputStream is = ();
			os = new FileOutputStream(fileSavePath);
			byte buf[] = new byte[1024];
			int count = 0;
			while ((count = (buf)) != -1) {
				(buf, 0, count);
			}
			();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (os != null) {
				try {
					();
				} catch (IOException e) {
					os = null;
					throw new RuntimeException(e);
				} finally {
					if (con != null) {
						();
						con = null;
					}
				}
			}
			if (br != null) {
				try {
					();
				} catch (IOException e) {
					br = null;
					throw new RuntimeException(e);
				} finally {
					if (con != null) {
						();
						con = null;
					}
				}
			}
		}
	}
 
	/**
	  * @Description: Send get request using HttpURLConnection
	  * @author:liuyc
	  * @time: May 17, 2016 at 3:27:29 pm
	  */
	public static String sendGet(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		StringBuffer resultBuffer = null;
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; entry : ()) {
				(());
				("=");
				(());
				("&amp;");
			}
		}
		HttpURLConnection con = null;
		BufferedReader br = null;
		try {
			URL url = null;
			if (sbParams != null &amp;&amp; () &gt; 0) {
				url = new URL(urlParam + "?" + (0, () - 1));
			} else {
				url = new URL(urlParam);
			}
			con = (HttpURLConnection) ();
			("Content-Type", "application/x-www-form-urlencoded");
			();
			resultBuffer = new StringBuffer();
			br = new BufferedReader(new InputStreamReader((), charset));
			String temp;
			while ((temp = ()) != null) {
				(temp);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null) {
				try {
					();
				} catch (IOException e) {
					br = null;
					throw new RuntimeException(e);
				} finally {
					if (con != null) {
						();
						con = null;
					}
				}
			}
		}
		return ();
	}
 
	/**
	  * @Description: Use URLConnection to send a get request
	  * @author:liuyc
	  * @time: May 17, 2016 at 3:27:58 pm
	  */
	public static String sendGet2(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		StringBuffer resultBuffer = null;
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; entry : ()) {
				(());
				("=");
				(());
				("&amp;");
			}
		}
		BufferedReader br = null;
		try {
			URL url = null;
			if (sbParams != null &amp;&amp; () &gt; 0) {
				url = new URL(urlParam + "?" + (0, () - 1));
			} else {
				url = new URL(urlParam);
			}
			URLConnection con = ();
			// Set request properties			("accept", "*/*");
			 ("connection", "Keep-Alive");
			 ("Content-Type", "application/x-www-form-urlencoded");
			 ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			 // Create a connection
			 ();
			 resultBuffer = new StringBuffer();
			 br = new BufferedReader(new InputStreamReader((), charset));
			 String temp;
			 while ((temp = ()) != null) {
				 (temp);
			 }
		 } catch (Exception e) {
			 throw new RuntimeException(e);
		 } finally {
			 if (br != null) {
				 try {
					 ();
				 } catch (IOException e) {
					 br = null;
					 throw new RuntimeException(e);
				 }
			 }
		 }
		 return ();
	 }
 
	 /**
	  * @Description: Send post request using HttpClient
	  * @author:liuyc
	  * @time: May 17, 2016 at 3:28:23 pm
	  */
	public static String httpClientPost(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		StringBuffer resultBuffer = null;
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(urlParam);
		// Build request parameters		List&lt;NameValuePair&gt; list = new ArrayList&lt;NameValuePair&gt;();
		Iterator&lt;Entry&lt;String, Object&gt;&gt; iterator = ().iterator();
		while (()) {
			Entry&lt;String, Object&gt; elem = ();
			(new BasicNameValuePair((), (())));
		}
		BufferedReader br = null;
		try {
			if (() &gt; 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				(entity);
			}
			HttpResponse response = (httpPost);
			// Read server response data			resultBuffer = new StringBuffer();
			br = new BufferedReader(new InputStreamReader(().getContent()));
			String temp;
			while ((temp = ()) != null) {
				(temp);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null) {
				try {
					();
				} catch (IOException e) {
					br = null;
					throw new RuntimeException(e);
				}
			}
		}
		return ();
	}
 
	/**
	  * @Description: Send get request using HttpClient
	  * @author:liuyc
	  * @time: May 17, 2016 at 3:28:56 pm
	  */
	public static String httpClientGet(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		StringBuffer resultBuffer = null;
		HttpClient client = new DefaultHttpClient();
		BufferedReader br = null;
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; entry : ()) {
				(());
				("=");
				try {
					(((()), charset));
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e);
				}
				("&amp;");
			}
		}
		if (sbParams != null &amp;&amp; () &gt; 0) {
			urlParam = urlParam + "?" + (0, () - 1);
		}
		HttpGet httpGet = new HttpGet(urlParam);
		try {
			HttpResponse response = (httpGet);
			// Read server response data			br = new BufferedReader(new InputStreamReader(().getContent()));
			String temp;
			resultBuffer = new StringBuffer();
			while ((temp = ()) != null) {
				(temp);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (br != null) {
				try {
					();
				} catch (IOException e) {
					br = null;
					throw new RuntimeException(e);
				}
			}
		}
		return ();
	}
 
	/**
	  * @Description: Use socket to send post request
	  * @author:liuyc
	  * @time: May 18, 2016 at 9:26:22 am
	  */
	public static String sendSocketPost(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		String result = "";
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; entry : ()) {
				(());
				("=");
				(());
				("&amp;");
			}
		}
		Socket socket = null;
		OutputStreamWriter osw = null;
		InputStream is = null;
		try {
			URL url = new URL(urlParam);
			String host = ();
			int port = ();
			if (-1 == port) {
				port = 80;
			}
			String path = ();
			socket = new Socket(host, port);
			StringBuffer sb = new StringBuffer();
			("POST " + path + " HTTP/1.1\r\n");
			("Host: " + host + "\r\n");
			("Connection: Keep-Alive\r\n");
			("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
			("Content-Length: ").append(().getBytes().length).append("\r\n");
			// Here is a carriage return line break, which means that the message header is finished, otherwise the server will continue to wait			("\r\n");
			if (sbParams != null &amp;&amp; () &gt; 0) {
				((0, () - 1));
			}
			osw = new OutputStreamWriter(());
			(());
			();
			is = ();
			String line = null;
			// Server response volume data length			int contentLength = 0;
			// Read the header information of http response			do {
				line = readLine(is, 0, charset);
				if (("Content-Length")) {
					// Get the length of the response body					contentLength = ((":")[1].trim());
				}
				// If a separate carriage return line break is encountered, the request header ends			} while (!("\r\n"));
			// Read out the response body data (that is the data you want)			result = readLine(is, contentLength, charset);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (osw != null) {
				try {
					();
				} catch (IOException e) {
					osw = null;
					throw new RuntimeException(e);
				} finally {
					if (socket != null) {
						try {
							();
						} catch (IOException e) {
							socket = null;
							throw new RuntimeException(e);
						}
					}
				}
			}
			if (is != null) {
				try {
					();
				} catch (IOException e) {
					is = null;
					throw new RuntimeException(e);
				} finally {
					if (socket != null) {
						try {
							();
						} catch (IOException e) {
							socket = null;
							throw new RuntimeException(e);
						}
					}
				}
			}
		}
		return result;
	}
 
	/**
	  * @Description: Use socket to send a get request
	  * @author:liuyc
	  * @time: May 18, 2016 at 9:27:18 am
	  */
	public static String sendSocketGet(String urlParam, Map&lt;String, Object&gt; params, String charset) {
		String result = "";
		// Build request parameters		StringBuffer sbParams = new StringBuffer();
		if (params != null &amp;&amp; () &gt; 0) {
			for (Entry&lt;String, Object&gt; entry : ()) {
				(());
				("=");
				(());
				("&amp;");
			}
		}
		Socket socket = null;
		OutputStreamWriter osw = null;
		InputStream is = null;
		try {
			URL url = new URL(urlParam);
			String host = ();
			int port = ();
			if (-1 == port) {
				port = 80;
			}
			String path = ();
			socket = new Socket(host, port);
			StringBuffer sb = new StringBuffer();
			("GET " + path + " HTTP/1.1\r\n");
			("Host: " + host + "\r\n");
			("Connection: Keep-Alive\r\n");
			("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
			("Content-Length: ").append(().getBytes().length).append("\r\n");
			// Here is a carriage return line break, which means that the message header is finished, otherwise the server will continue to wait			("\r\n");
			if (sbParams != null &amp;&amp; () &gt; 0) {
				((0, () - 1));
			}
			osw = new OutputStreamWriter(());
			(());
			();
			is = ();
			String line = null;
			// Server response volume data length			int contentLength = 0;
			// Read the header information of http response			do {
				line = readLine(is, 0, charset);
				if (("Content-Length")) {
					// Get the length of the response body					contentLength = ((":")[1].trim());
				}
				// If a separate carriage return line break is encountered, the request header ends			} while (!("\r\n"));
			// Read out the response body data (that is the data you want)			result = readLine(is, contentLength, charset);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (osw != null) {
				try {
					();
				} catch (IOException e) {
					osw = null;
					throw new RuntimeException(e);
				} finally {
					if (socket != null) {
						try {
							();
						} catch (IOException e) {
							socket = null;
							throw new RuntimeException(e);
						}
					}
				}
			}
			if (is != null) {
				try {
					();
				} catch (IOException e) {
					is = null;
					throw new RuntimeException(e);
				} finally {
					if (socket != null) {
						try {
							();
						} catch (IOException e) {
							socket = null;
							throw new RuntimeException(e);
						}
					}
				}
			}
		}
		return result;
	}
 
	/**
	  * @Description: Read a line of data. When the contentLe content length is 0, read the response header information. When it is not 0, read the main text.
	  * @time: May 17, 2016 at 6:11:07 pm
	  */
	private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
		List&lt;Byte&gt; lineByte = new ArrayList&lt;Byte&gt;();
		byte tempByte;
		int cumsum = 0;
		if (contentLength != 0) {
			do {
				tempByte = (byte) ();
				((tempByte));
				cumsum++;
			} while (cumsum &lt; contentLength);// cumsum equals contentLength means that it has been read		} else {
			do {
				tempByte = (byte) ();
				((tempByte));
			} while (tempByte != 10);// The ascii code value of the newline character is 10		}
 
		byte[] resutlBytes = new byte[()];
		for (int i = 0; i &lt; (); i++) {
			resutlBytes[i] = ((i)).byteValue();
		}
		return new String(resutlBytes, charset);
	}
	
}

The above four methods can send get and post requests respectively

  • The first type: HttpURLConnection,
  • Type 2: URLConnection,
  • The third type: HttpClient,
  • The 4th type: Socket. Friends should note that when using the 3rd type HttpClient, it is necessary to rely on three jar packages, namely: commons-logging-1.0., and httpcore-4.1.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.