下面介紹兩種方式
1.使用jdk提供的URLConnection
2.使用apache提供的HttpClient(封裝了jdk)
一、使用URLConnect進行http請求
1 public class HttpUtil { 2 3 /** 4 * 向指定URL發送GET方法的請求 5 * 6 * @param url 7 * 發送請求的URL 8 * @param param 9 * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 10 * @return URL 所代表遠程資源的響應結果 11 */ 12 public static String sendGet(String url, String param) { 13 String result = ""; 14 BufferedReader in = null; 15 try { 16 String urlNameString = url + "?" + param; 17 URL realUrl = new URL(urlNameString); 18 // 打開和URL之間的連接 19 URLConnection connection = realUrl.openConnection(); 20 // 設置通用的請求屬性 21 connection.setRequestProperty("accept", "*/*"); 22 connection.setRequestProperty("connection", "Keep-Alive"); 23 connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 24 // 建立實際的連接 25 connection.connect(); 26 // 獲取所有響應頭字段 27 Map<String, List<String>> map = connection.getHeaderFields(); 28 // 遍歷所有的響應頭字段 29 for (String key : map.keySet()) { 30 System.out.println(key + "--->" + map.get(key)); 31 } 32 // 定義 BufferedReader輸入流來讀取URL的響應 33 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 34 String line; 35 while ((line = in.readLine()) != null) { 36 result += line; 37 } 38 } catch (Exception e) { 39 System.out.println("發送GET請求出現異常!" + e); 40 e.printStackTrace(); 41 } 42 // 使用finally塊來關閉輸入流 43 finally { 44 try { 45 if (in != null) { 46 in.close(); 47 } 48 } catch (Exception e2) { 49 e2.printStackTrace(); 50 } 51 } 52 return result; 53 } 54 55 /** 56 * 向指定 URL 發送POST方法的請求 57 * 58 * @param url 59 * 發送請求的 URL 60 * @param param 61 * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 62 * @return 所代表遠程資源的響應結果 63 */ 64 public static String sendPost(String url, String param) { 65 PrintWriter out = null; 66 BufferedReader in = null; 67 String result = ""; 68 try { 69 URL realUrl = new URL(url); 70 // 打開和URL之間的連接 71 URLConnection conn = realUrl.openConnection(); 72 // 設置通用的請求屬性 73 conn.setRequestProperty("accept", "*/*"); 74 conn.setRequestProperty("connection", "Keep-Alive"); 75 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 76 // 發送POST請求必須設置如下兩行 77 conn.setDoOutput(true); 78 conn.setDoInput(true); 79 // 獲取URLConnection對象對應的輸出流 80 out = new PrintWriter(conn.getOutputStream()); 81 // 發送請求參數 82 out.print(param); 83 // flush輸出流的緩沖 84 out.flush(); 85 // 定義BufferedReader輸入流來讀取URL的響應 86 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 87 String line; 88 while ((line = in.readLine()) != null) { 89 result += line; 90 } 91 } catch (Exception e) { 92 System.out.println("發送 POST 請求出現異常!" + e); 93 e.printStackTrace(); 94 } 95 // 使用finally塊來關閉輸出流、輸入流 96 finally { 97 try { 98 if (out != null) { 99 out.close(); 100 } 101 if (in != null) { 102 in.close(); 103 } 104 } catch (IOException ex) { 105 ex.printStackTrace(); 106 } 107 } 108 return result; 109 } 110 111 public static void main(String[] args) { 112 // 發送 GET 請求 113 String result = HttpUtil.sendGet("http://baidu.com", "key=123&v=456"); 114 System.out.println("result: " + result); 115 System.out.println("-----------------------------------------------------"); 116 // 發送 POST 請求 117 String sr = HttpUtil.sendPost("http://baidu.com", "key=123&v=456"); 118 System.out.println("sr: " + sr); 119 } 120 }
二、使用HttpClient進行http請求
maven依賴:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency>
代碼:
public class HttpClientUtil { public static void get() { /** * client和response需要關閉資源 */ // 創建client,放入try()中自動釋放,不需要finally try (CloseableHttpClient client = HttpClientBuilder.create().build()) { // 執行得到response try (CloseableHttpResponse response = client.execute(new HttpGet("http://www.baidu.com"))) { // 獲取statusCode Integer statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { // body String bodyAsString = EntityUtils.toString(entity); // Media Type String contentMimeType = ContentType.getOrDefault(entity).getMimeType(); // head Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); // 輸出 System.out.println("statusCode:" + statusCode); System.out.println("contentMinmeType:" + contentMimeType); System.out.println("body:" + bodyAsString); System.out.println("head" + headers); } } } catch (IOException e) { e.printStackTrace(); } } public static void post() { // 創建client try (CloseableHttpClient client = HttpClientBuilder.create().build()) { HttpPost postRequest = new HttpPost("http://www.baidu.com"); // 添加請求參數 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("key1", "value1")); params.add(new BasicNameValuePair("key2", "value2")); postRequest.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8)); // 執行並獲取返回結果到response try (CloseableHttpResponse response = client.execute(postRequest)) { // 獲取statusCode Integer statusCode = response.getStatusLine().getStatusCode(); // Media Type String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType(); // body String bodyAsString = EntityUtils.toString(response.getEntity()); // head Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE); System.out.println("statusCode:" + statusCode); System.out.println("contentMinmeType:" + contentMimeType); System.out.println("body:" + bodyAsString); System.out.println("head" + headers); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { get(); System.out.println("------------------------------------"); post(); } }
轉載:
https://blog.csdn.net/ludonglue/article/details/78038643