目前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比較原生的一種實現方式。html
第一種方式:java原生HttpURLConnectionjava
package com.mobile.utils; import com.alibaba.fastjson.JSONObject; import org.apache.log4j.Logger; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; public class HttpUtil { static Logger log = Logger.getLogger(HttpUtil.class); /** * 向指定URL發送GET方法的請求 * * @param httpurl * 請求參數用?拼接在url後邊,請求參數應該是 name1=value1&name2=value2 的形式。 * @return result 所表明遠程資源的響應結果 */ public static String doGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回結果字符串 try { // 建立遠程url鏈接對象 URL url = new URL(httpurl); // 經過遠程url鏈接對象打開一個鏈接,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設置鏈接方式:get connection.setRequestMethod("GET"); // 設置鏈接主機服務器的超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設置讀取遠程返回的數據時間:60000毫秒 connection.setReadTimeout(60000); // 發送請求 connection.connect(); // 經過connection鏈接,獲取輸入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封裝輸入流is,並指定字符集 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); // 存放數據 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 關閉遠程鏈接 } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param httpUrl * 發送請求的 URL * @param param * 請求參數應該是{"key":"==g43sEvsUcbcunFv3mHkIzlHO4iiUIT R7WwXuSVKTK0yugJnZSlr6qNbxsL8OqCUAFyCDCoRKQ882m6cTTi0q9uCJsq JJvxS+8mZVRP/7lWfEVt8/N9mKplUA68SWJEPSXyz4MDeFam766KEyvqZ99d"}的形式。 * @return 所表明遠程資源的響應結果 */ public static String doPost(String httpUrl, String param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 經過遠程url鏈接對象打開鏈接 connection = (HttpURLConnection) url.openConnection(); // 設置鏈接請求方式 connection.setRequestMethod("POST"); // 設置鏈接主機服務器超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設置讀取主機服務器返回數據超時時間:60000毫秒 connection.setReadTimeout(60000); // 默認值爲:false,當向遠程服務器傳送數據/寫數據時,須要設置爲true connection.setDoOutput(true); // 默認值爲:true,當前向遠程服務讀取數據時,設置爲true,該參數無關緊要 connection.setDoInput(true); // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/json"); // 設置鑑權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 //connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 經過鏈接對象獲取一個輸出流 os = connection.getOutputStream(); // 經過輸出流對象將參數寫出去/傳輸出去,它是經過字節數組寫出的 os.write(param.getBytes()); // 經過鏈接對象獲取一個輸入流,向遠程讀取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 對輸入流對象進行包裝:charset根據工做項目組的要求來設置 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 循環遍歷一行一行讀取數據 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 斷開與遠程地址url的鏈接 connection.disconnect(); } return result; } /** * * @param httpUrl 請求的url * @param param form表單的參數(key,value形式) * @return */ public static String doPostForm(String httpUrl, Map param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 經過遠程url鏈接對象打開鏈接 connection = (HttpURLConnection) url.openConnection(); // 設置鏈接請求方式 connection.setRequestMethod("POST"); // 設置鏈接主機服務器超時時間:15000毫秒 connection.setConnectTimeout(15000); // 設置讀取主機服務器返回數據超時時間:60000毫秒 connection.setReadTimeout(60000); // 默認值爲:false,當向遠程服務器傳送數據/寫數據時,須要設置爲true connection.setDoOutput(true); // 默認值爲:true,當前向遠程服務讀取數據時,設置爲true,該參數無關緊要 connection.setDoInput(true); // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設置鑑權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 //connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 經過鏈接對象獲取一個輸出流 os = connection.getOutputStream(); // 經過輸出流對象將參數寫出去/傳輸出去,它是經過字節數組寫出的(form表單形式的參數實質也是key,value值的拼接,相似於get請求參數的拼接) os.write(createLinkString(param).getBytes()); // 經過鏈接對象獲取一個輸入流,向遠程讀取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 對輸入流對象進行包裝:charset根據工做項目組的要求來設置 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 循環遍歷一行一行讀取數據 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 斷開與遠程地址url的鏈接 connection.disconnect(); } return result; } /** * 把數組全部元素排序,並按照「參數=參數值」的模式用「&」字符拼接成字符串 * @param params 須要排序並參與字符拼接的參數組 * @return 拼接後字符串 */ public static String createLinkString(Map<String, String> params) { List<String> keys = new ArrayList<String>(params.keySet()); Collections.sort(keys); StringBuilder prestr = new StringBuilder(); for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value = params.get(key); if (i == keys.size() - 1) {// 拼接時,不包括最後一個&字符 prestr.append(key).append("=").append(value); } else { prestr.append(key).append("=").append(value).append("&"); } } return prestr.toString(); } public static void main(String[] args) { String url = "http://localhost:8082/api/conf/findConfList?type=1"; String getResult = HttpUtil.doGet(url); System.out.println(getResult); url = "http://localhost:8082/api/core/login"; JSONObject json = new JSONObject(); json.put("key", "==g43sEvsUcbcunFv3mHkIzlHO4iiUIT R7WwXuSVKTK0yugJnZSlr6qNbxsL8OqCUAFyCDCoRKQ882m6cTTi0q9uCJsq JJvxS+8mZVRP/7lWfEVt8/N9mKplUA68SWJEPSXyz4MDeFam766KEyvqZ99d"); String postResult = HttpUtil.doPost(url, json.toJSONString()); System.out.println(postResult); url = "http://localhost:8082/api/test/testSendForm"; Map<String,String> map = new HashMap<>(); map.put("name", "測試表單請求"); String formResult = HttpUtil.doPostForm(url, map); System.out.println(formResult); } }
以上包括了get請求和post請求以及form表單請求 apache
第二種方式:apache HttpClient 3.1json
package com.demo.httpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class HttpClient3 { public static String doGet(String url) { // 輸入流 InputStream is = null; BufferedReader br = null; String result = null; // 建立httpClient實例 HttpClient httpClient = new HttpClient(); // 設置http鏈接主機服務超時時間:15000毫秒 // 先獲取鏈接管理器對象,再獲取參數對象,再進行參數的賦值 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); // 建立一個Get方法實例對象 GetMethod getMethod = new GetMethod(url); // 設置get請求超時爲60000毫秒 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); // 設置請求重試機制,默認重試次數:3次,參數設置爲true,重試機制可用,false相反 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); try { // 執行Get方法 int statusCode = httpClient.executeMethod(getMethod); // 判斷返回碼 if (statusCode != HttpStatus.SC_OK) { // 若是狀態碼返回的不是ok,說明失敗了,打印錯誤信息 System.err.println("Method faild: " + getMethod.getStatusLine()); } else { // 經過getMethod實例,獲取遠程的一個輸入流 is = getMethod.getResponseBodyAsStream(); // 包裝輸入流 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); // 讀取封裝的輸入流 String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp).append("\r\n"); } result = sbf.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 釋放鏈接 getMethod.releaseConnection(); } return result; } public static String doPost(String url, Map<String, Object> paramMap) { // 獲取輸入流 InputStream is = null; BufferedReader br = null; String result = null; // 建立httpClient實例對象 HttpClient httpClient = new HttpClient(); // 設置httpClient鏈接主機服務器超時時間:15000毫秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); // 建立post請求方法實例對象 PostMethod postMethod = new PostMethod(url); // 設置post請求超時時間 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); NameValuePair[] nvp = null; // 判斷參數map集合paramMap是否爲空 if (null != paramMap && paramMap.size() > 0) {// 不爲空 // 建立鍵值參數對象數組,大小爲參數的個數 nvp = new NameValuePair[paramMap.size()]; // 循環遍歷參數集合map Set<Entry<String, Object>> entrySet = paramMap.entrySet(); // 獲取迭代器 Iterator<Entry<String, Object>> iterator = entrySet.iterator(); int index = 0; while (iterator.hasNext()) { Entry<String, Object> mapEntry = iterator.next(); // 從mapEntry中獲取key和value建立鍵值對象存放到數組中 try { nvp[index] = new NameValuePair(mapEntry.getKey(), new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } index++; } } // 判斷nvp數組是否爲空 if (null != nvp && nvp.length > 0) { // 將參數存放到requestBody對象中 postMethod.setRequestBody(nvp); } // 執行POST方法 try { int statusCode = httpClient.executeMethod(postMethod); // 判斷是否成功 if (statusCode != HttpStatus.SC_OK) { System.err.println("Method faild: " + postMethod.getStatusLine()); } // 獲取遠程返回的數據 is = postMethod.getResponseBodyAsStream(); // 封裝輸入流 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp).append("\r\n"); } result = sbf.toString(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 釋放鏈接 postMethod.releaseConnection(); } return result; } }
第三種方式:apache httpClient4.5api
package com.mobile.utils; import com.alibaba.fastjson.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.*; import java.util.Map.Entry; public class HttpUtil { static Logger log = Logger.getLogger(HttpUtil.class);public static void main(String[] args) { String url = "http://localhost:8082/api/conf/findConfList?type=1"; String getResult = HttpUtil.getData(url); System.out.println(getResult); url = "http://localhost:8082/api/core/login"; JSONObject json = new JSONObject(); json.put("key", "==g43sEvsUcbcunFv3mHkIzlHO4iiUIT R7WwXuSVKTK0yugJnZSlr6qNbxsL8OqCUAFyCDCoRKQ882m6cTTi0q9uCJsq JJvxS+8mZVRP/7lWfEVt8/N9mKplUA68SWJEPSXyz4MDeFam766KEyvqZ99d"); String postResult = HttpUtil.postData(url, json); System.out.println(postResult); url = "http://localhost:8082/api/test/testSendForm?format=json"; Map<String, Object> map = new HashMap<>(); map.put("name", "測試表單請求"); String formResult = HttpUtil.sendxwwwForm(url, map); System.out.println(formResult); } public static String getData(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String result = ""; try { // 經過址默認配置建立一個httpClient實例 httpClient = HttpClients.createDefault(); // 建立httpGet遠程鏈接實例 HttpGet httpGet = new HttpGet(url); // 設置請求頭信息,鑑權 httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 設置配置請求參數 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 鏈接主機服務超時時間 .setConnectionRequestTimeout(35000)// 請求超時時間 .setSocketTimeout(60000)// 數據讀取超時時間 .build(); // 爲httpGet實例設置配置 httpGet.setConfig(requestConfig); // 執行get請求獲得返回對象 response = httpClient.execute(httpGet); // 經過返回對象獲取返回數據 HttpEntity entity = response.getEntity(); // 經過EntityUtils中的toString方法將結果轉換爲字符串 result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != response) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static String postData(String url, Map<String, Object> paramMap) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); HttpPost post = new HttpPost(url); String result = ""; try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) { // HttpEntity entity = new StringEntity(jsonStrData); // 修復 POST json 致使中文亂碼 HttpEntity entity = new StringEntity(paramMap.toString(), "UTF-8"); post.setEntity(entity); post.setHeader("Content-type", "application/json"); HttpResponse resp = closeableHttpClient.execute(post); try { InputStream respIs = resp.getEntity().getContent(); byte[] respBytes = IOUtils.toByteArray(respIs); result = new String(respBytes, Charset.forName("UTF-8")); } catch (Exception e) { e.printStackTrace(); } return result; } catch (IOException e) { e.printStackTrace(); } return result; } /** * form表單提交 * @param url * @param paramMap * @return */ public static String sendxwwwform(String url, Map<String, Object> paramMap) { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; String result = ""; // 建立httpClient實例 httpClient = HttpClients.createDefault(); // 建立httpPost遠程鏈接實例 HttpPost httpPost = new HttpPost(url); // 配置請求參數實例 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設置鏈接主機服務超時時間 .setConnectionRequestTimeout(35000)// 設置鏈接請求超時時間 .setSocketTimeout(60000)// 設置讀取數據鏈接超時時間 .build(); // 爲httpPost實例設置配置 httpPost.setConfig(requestConfig); // 設置請求頭 httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 封裝post請求參數 if (null != paramMap && paramMap.size() > 0) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); // 經過map集成entrySet方法獲取entity Set<Entry<String, Object>> entrySet = paramMap.entrySet(); // 循環遍歷,獲取迭代器 Iterator<Entry<String, Object>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry<String, Object> mapEntry = iterator.next(); nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString())); } // 爲httpPost設置封裝好的請求參數 try { httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } try { // httpClient對象執行post請求,並返回響應參數對象 httpResponse = httpClient.execute(httpPost); // 從響應對象中獲取響應內容 HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != httpResponse) { try { httpResponse.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
以上包括了get請求和post請求以及form表單請求 數組
此外還能夠設置添加自定義請求頭(有的接口須要登陸驗證):服務器
方式一:app
//設置自定義請求頭 if (headerMap != null) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { connection.setRequestProperty(entry.getKey(),entry.getValue()); } }
方式三:框架
if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpPost.addHeader(entry.getKey(),entry.getValue()); } }
轉載自https://www.cnblogs.com/hhhshct/p/8523697.html工具
測試後,稍做改動及添加
httpurlconnection和httpclient區別:http://www.javashuo.com/article/p-nwxfdsxd-cr.html