Java發送http請求網上很多資料,這里只是記錄一下我的一個工具類。直接代碼了。
package com.JohanChan; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; public class HttpUtils { /** * 向指定服務器發送GET請求 * */ private static int defTimeOut = 2500; public static String sendGet(String url,Integer timeOut) { BufferedReader in = null; try { if (timeOut == null || timeOut <= 0) timeOut = defTimeOut; URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setConnectTimeout(timeOut); connection.setReadTimeout(timeOut); // 建立實際的連接 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = in.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return null; } //post請求方法 public static String sendPost(String url, String data) { String response = null; try { CloseableHttpClient httpclient = null; CloseableHttpResponse httpresponse = null; try { httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); // 構造消息頭 // httppost.setHeader("Host","192.168.0.231:18080"); httppost.setHeader("Content-type", "application/json; charset=utf-8"); // httppost.setHeader("Connection", " keep-alive"); /*if (StringUtils.isNotEmpty(auth)){ httppost.setHeader("Authorization",auth); httppost.setHeader("Origin","http://192.168.0.231:18080"); }*/ StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", "UTF-8")); stringentity.setContentType("application/json"); httppost.setEntity(stringentity); httpresponse = httpclient.execute(httppost); response = EntityUtils.toString(httpresponse.getEntity(), "UTF-8"); } finally { if (httpclient != null) { httpclient.close(); } if (httpresponse != null) { httpresponse.close(); } } } catch (Exception e) { e.printStackTrace(); } return response; } }