目前JAVA實現HTTP請求的方法用的最多的有兩種:一種是通過HTTPClient這種第三方的開源框架去實現。HTTPClient對HTTP的封裝性比較不錯,通過它基本上能夠滿足我們大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作遠程 url的工具包,雖然已不再更新,但實現工作中使用httpClient3.1的代碼還是很多,HttpClient4.5是org.apache.http.client下操作遠程 url的工具包,最新的;另一種則是通過HttpURLConnection去實現,HttpURLConnection是JAVA的標准類,是JAVA比較原生的一種實現方式。
第一種方式:java原生HttpURLConnection
1 package com.powerX.httpClient; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStream; 8 import java.net.HttpURLConnection; 9 import java.net.MalformedURLException; 10 import java.net.URL; 11 12 public class HttpClient { 13 public static String doGet(String httpurl) { 14 HttpURLConnection connection = null; 15 InputStream is = null; 16 BufferedReader br = null; 17 String result = null;// 返回結果字符串 18 try { 19 // 創建遠程url連接對象 20 URL url = new URL(httpurl); 21 // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類 22 connection = (HttpURLConnection) url.openConnection(); 23 // 設置連接方式:get 24 connection.setRequestMethod("GET"); 25 // 設置連接主機服務器的超時時間:15000毫秒 26 connection.setConnectTimeout(15000); 27 // 設置讀取遠程返回的數據時間:60000毫秒 28 connection.setReadTimeout(60000); 29 // 發送請求 30 connection.connect(); 31 // 通過connection連接,獲取輸入流 32 if (connection.getResponseCode() == 200) { 33 is = connection.getInputStream(); 34 // 封裝輸入流is,並指定字符集 35 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 36 // 存放數據 37 StringBuffer sbf = new StringBuffer(); 38 String temp = null; 39 while ((temp = br.readLine()) != null) { 40 sbf.append(temp); 41 sbf.append("\r\n"); 42 } 43 result = sbf.toString(); 44 } 45 } catch (MalformedURLException e) { 46 e.printStackTrace(); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 } finally { 50 // 關閉資源 51 if (null != br) { 52 try { 53 br.close(); 54 } catch (IOException e) { 55 e.printStackTrace(); 56 } 57 } 58 59 if (null != is) { 60 try { 61 is.close(); 62 } catch (IOException e) { 63 e.printStackTrace(); 64 } 65 } 66 67 connection.disconnect();// 關閉遠程連接 68 } 69 70 return result; 71 } 72 73 public static String doPost(String httpUrl, String param) { 74 75 HttpURLConnection connection = null; 76 InputStream is = null; 77 OutputStream os = null; 78 BufferedReader br = null; 79 String result = null; 80 try { 81 URL url = new URL(httpUrl); 82 // 通過遠程url連接對象打開連接 83 connection = (HttpURLConnection) url.openConnection(); 84 // 設置連接請求方式 85 connection.setRequestMethod("POST"); 86 // 設置連接主機服務器超時時間:15000毫秒 87 connection.setConnectTimeout(15000); 88 // 設置讀取主機服務器返回數據超時時間:60000毫秒 89 connection.setReadTimeout(60000); 90 91 // 默認值為:false,當向遠程服務器傳送數據/寫數據時,需要設置為true 92 connection.setDoOutput(true); 93 // 默認值為:true,當前向遠程服務讀取數據時,設置為true,該參數可有可無 94 connection.setDoInput(true); 95 // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。 96 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 97 // 設置鑒權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 98 connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); 99 // 通過連接對象獲取一個輸出流 100 os = connection.getOutputStream(); 101 // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的 102 os.write(param.getBytes()); 103 // 通過連接對象獲取一個輸入流,向遠程讀取 104 if (connection.getResponseCode() == 200) { 105 106 is = connection.getInputStream(); 107 // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置 108 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 109 110 StringBuffer sbf = new StringBuffer(); 111 String temp = null; 112 // 循環遍歷一行一行讀取數據 113 while ((temp = br.readLine()) != null) { 114 sbf.append(temp); 115 sbf.append("\r\n"); 116 } 117 result = sbf.toString(); 118 } 119 } catch (MalformedURLException e) { 120 e.printStackTrace(); 121 } catch (IOException e) { 122 e.printStackTrace(); 123 } finally { 124 // 關閉資源 125 if (null != br) { 126 try { 127 br.close(); 128 } catch (IOException e) { 129 e.printStackTrace(); 130 } 131 } 132 if (null != os) { 133 try { 134 os.close(); 135 } catch (IOException e) { 136 e.printStackTrace(); 137 } 138 } 139 if (null != is) { 140 try { 141 is.close(); 142 } catch (IOException e) { 143 e.printStackTrace(); 144 } 145 } 146 // 斷開與遠程地址url的連接 147 connection.disconnect(); 148 } 149 return result; 150 } 151 }
第二種方式:apache HttpClient3.1
1 package com.powerX.httpClient; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.UnsupportedEncodingException; 8 import java.util.Iterator; 9 import java.util.Map; 10 import java.util.Map.Entry; 11 import java.util.Set; 12 13 import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; 14 import org.apache.commons.httpclient.HttpClient; 15 import org.apache.commons.httpclient.HttpStatus; 16 import org.apache.commons.httpclient.NameValuePair; 17 import org.apache.commons.httpclient.methods.GetMethod; 18 import org.apache.commons.httpclient.methods.PostMethod; 19 import org.apache.commons.httpclient.params.HttpMethodParams; 20 21 public class HttpClient3 { 22 23 public static String doGet(String url) { 24 // 輸入流 25 InputStream is = null; 26 BufferedReader br = null; 27 String result = null; 28 // 創建httpClient實例 29 HttpClient httpClient = new HttpClient(); 30 // 設置http連接主機服務超時時間:15000毫秒 31 // 先獲取連接管理器對象,再獲取參數對象,再進行參數的賦值 32 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); 33 // 創建一個Get方法實例對象 34 GetMethod getMethod = new GetMethod(url); 35 // 設置get請求超時為60000毫秒 36 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); 37 // 設置請求重試機制,默認重試次數:3次,參數設置為true,重試機制可用,false相反 38 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); 39 try { 40 // 執行Get方法 41 int statusCode = httpClient.executeMethod(getMethod); 42 // 判斷返回碼 43 if (statusCode != HttpStatus.SC_OK) { 44 // 如果狀態碼返回的不是ok,說明失敗了,打印錯誤信息 45 System.err.println("Method faild: " + getMethod.getStatusLine()); 46 } else { 47 // 通過getMethod實例,獲取遠程的一個輸入流 48 is = getMethod.getResponseBodyAsStream(); 49 // 包裝輸入流 50 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 51 52 StringBuffer sbf = new StringBuffer(); 53 // 讀取封裝的輸入流 54 String temp = null; 55 while ((temp = br.readLine()) != null) { 56 sbf.append(temp).append("\r\n"); 57 } 58 59 result = sbf.toString(); 60 } 61 62 } catch (IOException e) { 63 e.printStackTrace(); 64 } finally { 65 // 關閉資源 66 if (null != br) { 67 try { 68 br.close(); 69 } catch (IOException e) { 70 e.printStackTrace(); 71 } 72 } 73 if (null != is) { 74 try { 75 is.close(); 76 } catch (IOException e) { 77 e.printStackTrace(); 78 } 79 } 80 // 釋放連接 81 getMethod.releaseConnection(); 82 } 83 return result; 84 } 85 86 public static String doPost(String url, Map<String, Object> paramMap) { 87 // 獲取輸入流 88 InputStream is = null; 89 BufferedReader br = null; 90 String result = null; 91 // 創建httpClient實例對象 92 HttpClient httpClient = new HttpClient(); 93 // 設置httpClient連接主機服務器超時時間:15000毫秒 94 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); 95 // 創建post請求方法實例對象 96 PostMethod postMethod = new PostMethod(url); 97 // 設置post請求超時時間 98 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); 99 100 NameValuePair[] nvp = null; 101 // 判斷參數map集合paramMap是否為空 102 if (null != paramMap && paramMap.size() > 0) {// 不為空 103 // 創建鍵值參數對象數組,大小為參數的個數 104 nvp = new NameValuePair[paramMap.size()]; 105 // 循環遍歷參數集合map 106 Set<Entry<String, Object>> entrySet = paramMap.entrySet(); 107 // 獲取迭代器 108 Iterator<Entry<String, Object>> iterator = entrySet.iterator(); 109 110 int index = 0; 111 while (iterator.hasNext()) { 112 Entry<String, Object> mapEntry = iterator.next(); 113 // 從mapEntry中獲取key和value創建鍵值對象存放到數組中 114 try { 115 nvp[index] = new NameValuePair(mapEntry.getKey(), 116 new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8")); 117 } catch (UnsupportedEncodingException e) { 118 e.printStackTrace(); 119 } 120 index++; 121 } 122 } 123 // 判斷nvp數組是否為空 124 if (null != nvp && nvp.length > 0) { 125 // 將參數存放到requestBody對象中 126 postMethod.setRequestBody(nvp); 127 } 128 // 執行POST方法 129 try { 130 int statusCode = httpClient.executeMethod(postMethod); 131 // 判斷是否成功 132 if (statusCode != HttpStatus.SC_OK) { 133 System.err.println("Method faild: " + postMethod.getStatusLine()); 134 } 135 // 獲取遠程返回的數據 136 is = postMethod.getResponseBodyAsStream(); 137 // 封裝輸入流 138 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 139 140 StringBuffer sbf = new StringBuffer(); 141 String temp = null; 142 while ((temp = br.readLine()) != null) { 143 sbf.append(temp).append("\r\n"); 144 } 145 146 result = sbf.toString(); 147 } catch (IOException e) { 148 e.printStackTrace(); 149 } finally { 150 // 關閉資源 151 if (null != br) { 152 try { 153 br.close(); 154 } catch (IOException e) { 155 e.printStackTrace(); 156 } 157 } 158 if (null != is) { 159 try { 160 is.close(); 161 } catch (IOException e) { 162 e.printStackTrace(); 163 } 164 } 165 // 釋放連接 166 postMethod.releaseConnection(); 167 } 168 return result; 169 } 170 }
第三種方式:apache httpClient4.5
1 package com.powerX.httpClient; 2 3 import java.io.IOException; 4 import java.io.UnsupportedEncodingException; 5 import java.util.ArrayList; 6 import java.util.Iterator; 7 import java.util.List; 8 import java.util.Map; 9 import java.util.Map.Entry; 10 import java.util.Set; 11 12 import org.apache.http.HttpEntity; 13 import org.apache.http.NameValuePair; 14 import org.apache.http.client.ClientProtocolException; 15 import org.apache.http.client.config.RequestConfig; 16 import org.apache.http.client.entity.UrlEncodedFormEntity; 17 import org.apache.http.client.methods.CloseableHttpResponse; 18 import org.apache.http.client.methods.HttpGet; 19 import org.apache.http.client.methods.HttpPost; 20 import org.apache.http.impl.client.CloseableHttpClient; 21 import org.apache.http.impl.client.HttpClients; 22 import org.apache.http.message.BasicNameValuePair; 23 import org.apache.http.util.EntityUtils; 24 25 public class HttpClient4 { 26 27 public static String doGet(String url) { 28 CloseableHttpClient httpClient = null; 29 CloseableHttpResponse response = null; 30 String result = ""; 31 try { 32 // 通過址默認配置創建一個httpClient實例 33 httpClient = HttpClients.createDefault(); 34 // 創建httpGet遠程連接實例 35 HttpGet httpGet = new HttpGet(url); 36 // 設置請求頭信息,鑒權 37 httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); 38 // 設置配置請求參數 39 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連接主機服務超時時間 40 .setConnectionRequestTimeout(35000)// 請求超時時間 41 .setSocketTimeout(60000)// 數據讀取超時時間 42 .build(); 43 // 為httpGet實例設置配置 44 httpGet.setConfig(requestConfig); 45 // 執行get請求得到返回對象 46 response = httpClient.execute(httpGet); 47 // 通過返回對象獲取返回數據 48 HttpEntity entity = response.getEntity(); 49 // 通過EntityUtils中的toString方法將結果轉換為字符串 50 result = EntityUtils.toString(entity); 51 } catch (ClientProtocolException e) { 52 e.printStackTrace(); 53 } catch (IOException e) { 54 e.printStackTrace(); 55 } finally { 56 // 關閉資源 57 if (null != response) { 58 try { 59 response.close(); 60 } catch (IOException e) { 61 e.printStackTrace(); 62 } 63 } 64 if (null != httpClient) { 65 try { 66 httpClient.close(); 67 } catch (IOException e) { 68 e.printStackTrace(); 69 } 70 } 71 } 72 return result; 73 } 74 75 public static String doPost(String url, Map<String, Object> paramMap) { 76 CloseableHttpClient httpClient = null; 77 CloseableHttpResponse httpResponse = null; 78 String result = ""; 79 // 創建httpClient實例 80 httpClient = HttpClients.createDefault(); 81 // 創建httpPost遠程連接實例 82 HttpPost httpPost = new HttpPost(url); 83 // 配置請求參數實例 84 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設置連接主機服務超時時間 85 .setConnectionRequestTimeout(35000)// 設置連接請求超時時間 86 .setSocketTimeout(60000)// 設置讀取數據連接超時時間 87 .build(); 88 // 為httpPost實例設置配置 89 httpPost.setConfig(requestConfig); 90 // 設置請求頭 91 httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); 92 // 封裝post請求參數 93 if (null != paramMap && paramMap.size() > 0) { 94 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 95 // 通過map集成entrySet方法獲取entity 96 Set<Entry<String, Object>> entrySet = paramMap.entrySet(); 97 // 循環遍歷,獲取迭代器 98 Iterator<Entry<String, Object>> iterator = entrySet.iterator(); 99 while (iterator.hasNext()) { 100 Entry<String, Object> mapEntry = iterator.next(); 101 nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString())); 102 } 103 104 // 為httpPost設置封裝好的請求參數 105 try { 106 httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); 107 } catch (UnsupportedEncodingException e) { 108 e.printStackTrace(); 109 } 110 } 111 try { 112 // httpClient對象執行post請求,並返回響應參數對象 113 httpResponse = httpClient.execute(httpPost); 114 // 從響應對象中獲取響應內容 115 HttpEntity entity = httpResponse.getEntity(); 116 result = EntityUtils.toString(entity); 117 } catch (ClientProtocolException e) { 118 e.printStackTrace(); 119 } catch (IOException e) { 120 e.printStackTrace(); 121 } finally { 122 // 關閉資源 123 if (null != httpResponse) { 124 try { 125 httpResponse.close(); 126 } catch (IOException e) { 127 e.printStackTrace(); 128 } 129 } 130 if (null != httpClient) { 131 try { 132 httpClient.close(); 133 } catch (IOException e) { 134 e.printStackTrace(); 135 } 136 } 137 } 138 return result; 139 } 140 }
原文轉載自 https://www.cnblogs.com/hhhshct/p/8523697.html