Java 实现 HTTP 请求的三种方式
除了本文推薦的幾種方式,強(qiáng)烈推薦 OkHttp
目前JAVA實現(xiàn)HTTP請求的方法用的最多的有兩種:一種是通過HTTPClient這種第三方的開源框架去實現(xiàn)。HTTPClient對HTTP的封裝性比較不錯,通過它基本上能夠滿足我們大部分的需求。
HttpClient3.1 是 org.apache.commons.httpclient下操作遠(yuǎn)程 url的工具包,雖然已不再更新,但實現(xiàn)工作中使用httpClient3.1的代碼還是很多,HttpClient4.5是org.apache.http.client下操作遠(yuǎn)程 url的工具包,最新的;
另一種則是通過HttpURLConnection去實現(xiàn),HttpURLConnection是JAVA的標(biāo)準(zhǔn)類,是JAVA比較原生的一種實現(xiàn)方式。
自己在工作中三種方式都用到過,總結(jié)一下分享給大家,也方便自己以后使用,話不多說上代碼。
第一種方式:java原生HttpURLConnection
package com.powerX.httpClient;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL;public class HttpClient {public static String doGet(String httpurl) {HttpURLConnection connection = null;InputStream is = null;BufferedReader br = null;String result = null;// 返回結(jié)果字符串try {// 創(chuàng)建遠(yuǎn)程url連接對象URL url = new URL(httpurl);// 通過遠(yuǎn)程url連接對象打開一個連接,強(qiáng)轉(zhuǎn)成httpURLConnection類connection = (HttpURLConnection) url.openConnection();// 設(shè)置連接方式:getconnection.setRequestMethod("GET");// 設(shè)置連接主機(jī)服務(wù)器的超時時間:15000毫秒connection.setConnectTimeout(15000);// 設(shè)置讀取遠(yuǎn)程返回的數(shù)據(jù)時間:60000毫秒connection.setReadTimeout(60000);// 發(fā)送請求connection.connect();// 通過connection連接,獲取輸入流if (connection.getResponseCode() == 200) {is = connection.getInputStream();// 封裝輸入流is,并指定字符集br = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 存放數(shù)據(jù)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 {// 關(guān)閉資源if (null != br) {try {br.close();} catch (IOException e) {e.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}connection.disconnect();// 關(guān)閉遠(yuǎn)程連接}return result;}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);// 通過遠(yuǎn)程url連接對象打開連接connection = (HttpURLConnection) url.openConnection();// 設(shè)置連接請求方式connection.setRequestMethod("POST");// 設(shè)置連接主機(jī)服務(wù)器超時時間:15000毫秒connection.setConnectTimeout(15000);// 設(shè)置讀取主機(jī)服務(wù)器返回數(shù)據(jù)超時時間:60000毫秒connection.setReadTimeout(60000);// 默認(rèn)值為:false,當(dāng)向遠(yuǎn)程服務(wù)器傳送數(shù)據(jù)/寫數(shù)據(jù)時,需要設(shè)置為trueconnection.setDoOutput(true);// 默認(rèn)值為:true,當(dāng)前向遠(yuǎn)程服務(wù)讀取數(shù)據(jù)時,設(shè)置為true,該參數(shù)可有可無connection.setDoInput(true);// 設(shè)置傳入?yún)?shù)的格式:請求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 設(shè)置鑒權(quán)信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");// 通過連接對象獲取一個輸出流os = connection.getOutputStream();// 通過輸出流對象將參數(shù)寫出去/傳輸出去,它是通過字節(jié)數(shù)組寫出的os.write(param.getBytes());// 通過連接對象獲取一個輸入流,向遠(yuǎn)程讀取if (connection.getResponseCode() == 200) {is = connection.getInputStream();// 對輸入流對象進(jìn)行包裝:charset根據(jù)工作項目組的要求來設(shè)置br = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String temp = null;// 循環(huán)遍歷一行一行讀取數(shù)據(jù)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 {// 關(guān)閉資源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();}}// 斷開與遠(yuǎn)程地址url的連接connection.disconnect();}return result;} }第二種方式:apache HttpClient3.1
package com.powerX.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;// 創(chuàng)建httpClient實例HttpClient httpClient = new HttpClient();// 設(shè)置http連接主機(jī)服務(wù)超時時間:15000毫秒// 先獲取連接管理器對象,再獲取參數(shù)對象,再進(jìn)行參數(shù)的賦值httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);// 創(chuàng)建一個Get方法實例對象GetMethod getMethod = new GetMethod(url);// 設(shè)置get請求超時為60000毫秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);// 設(shè)置請求重試機(jī)制,默認(rèn)重試次數(shù):3次,參數(shù)設(shè)置為true,重試機(jī)制可用,false相反getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));try {// 執(zhí)行Get方法int statusCode = httpClient.executeMethod(getMethod);// 判斷返回碼if (statusCode != HttpStatus.SC_OK) {// 如果狀態(tài)碼返回的不是ok,說明失敗了,打印錯誤信息System.err.println("Method faild: " + getMethod.getStatusLine());} else {// 通過getMethod實例,獲取遠(yuǎn)程的一個輸入流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 {// 關(guān)閉資源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;// 創(chuàng)建httpClient實例對象HttpClient httpClient = new HttpClient();// 設(shè)置httpClient連接主機(jī)服務(wù)器超時時間:15000毫秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);// 創(chuàng)建post請求方法實例對象PostMethod postMethod = new PostMethod(url);// 設(shè)置post請求超時時間postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);NameValuePair[] nvp = null;// 判斷參數(shù)map集合paramMap是否為空if (null != paramMap && paramMap.size() > 0) {// 不為空// 創(chuàng)建鍵值參數(shù)對象數(shù)組,大小為參數(shù)的個數(shù)nvp = new NameValuePair[paramMap.size()];// 循環(huán)遍歷參數(shù)集合mapSet<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創(chuàng)建鍵值對象存放到數(shù)組中try {nvp[index] = new NameValuePair(mapEntry.getKey(),new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}index++;}}// 判斷nvp數(shù)組是否為空if (null != nvp && nvp.length > 0) {// 將參數(shù)存放到requestBody對象中postMethod.setRequestBody(nvp);}// 執(zhí)行POST方法try {int statusCode = httpClient.executeMethod(postMethod);// 判斷是否成功if (statusCode != HttpStatus.SC_OK) {System.err.println("Method faild: " + postMethod.getStatusLine());}// 獲取遠(yuǎn)程返回的數(shù)據(jù)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 {// 關(guān)閉資源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.5
package com.powerX.httpClient;import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set;import org.apache.http.HttpEntity; 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.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;public class HttpClient4 {public static String doGet(String url) {CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;String result = "";try {// 通過址默認(rèn)配置創(chuàng)建一個httpClient實例httpClient = HttpClients.createDefault();// 創(chuàng)建httpGet遠(yuǎn)程連接實例HttpGet httpGet = new HttpGet(url);// 設(shè)置請求頭信息,鑒權(quán)httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");// 設(shè)置配置請求參數(shù)RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連接主機(jī)服務(wù)超時時間.setConnectionRequestTimeout(35000)// 請求超時時間.setSocketTimeout(60000)// 數(shù)據(jù)讀取超時時間.build();// 為httpGet實例設(shè)置配置httpGet.setConfig(requestConfig);// 執(zhí)行g(shù)et請求得到返回對象response = httpClient.execute(httpGet);// 通過返回對象獲取返回數(shù)據(jù)HttpEntity entity = response.getEntity();// 通過EntityUtils中的toString方法將結(jié)果轉(zhuǎn)換為字符串result = EntityUtils.toString(entity);} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 關(guān)閉資源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 doPost(String url, Map<String, Object> paramMap) {CloseableHttpClient httpClient = null;CloseableHttpResponse httpResponse = null;String result = "";// 創(chuàng)建httpClient實例httpClient = HttpClients.createDefault();// 創(chuàng)建httpPost遠(yuǎn)程連接實例HttpPost httpPost = new HttpPost(url);// 配置請求參數(shù)實例RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設(shè)置連接主機(jī)服務(wù)超時時間.setConnectionRequestTimeout(35000)// 設(shè)置連接請求超時時間.setSocketTimeout(60000)// 設(shè)置讀取數(shù)據(jù)連接超時時間.build();// 為httpPost實例設(shè)置配置httpPost.setConfig(requestConfig);// 設(shè)置請求頭httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");// 封裝post請求參數(shù)if (null != paramMap && paramMap.size() > 0) {List<NameValuePair> nvps = new ArrayList<NameValuePair>();// 通過map集成entrySet方法獲取entitySet<Entry<String, Object>> entrySet = paramMap.entrySet();// 循環(huán)遍歷,獲取迭代器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設(shè)置封裝好的請求參數(shù)try {httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}}try {// httpClient對象執(zhí)行post請求,并返回響應(yīng)參數(shù)對象httpResponse = httpClient.execute(httpPost);// 從響應(yīng)對象中獲取響應(yīng)內(nèi)容HttpEntity entity = httpResponse.getEntity();result = EntityUtils.toString(entity);} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 關(guān)閉資源if (null != httpResponse) {try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}if (null != httpClient) {try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}return result;} }有時候我們在使用post請求時,可能傳入的參數(shù)是json或者其他格式,此時我們則需要更改請求頭及參數(shù)的設(shè)置信息,以httpClient4.5為例,更改下面兩列配置:
httpPost.setEntity(new StringEntity("你的json串")); httpPost.addHeader("Content-Type", "application/json")。
總結(jié)
以上是生活随笔為你收集整理的Java 实现 HTTP 请求的三种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试问:Kafka 为什么速度那么快?
- 下一篇: JVM 最多支持多少个线程?