目前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
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;// 返回結果字符串
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;
}
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/x-www-form-urlencoded");
// 設置鑑權信息: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;
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
第二種方式: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;
// 創建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, MapparamMap) {
// 獲取輸入流
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> entrySet = paramMap.entrySet();
// 獲取迭代器
Iterator<entry> iterator = entrySet.iterator();
int index = 0;
while (iterator.hasNext()) {
EntrymapEntry = 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;
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
第三種方式: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 {
// 通過址默認配置創建一個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 doPost(String url, MapparamMap) {
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) {
Listnvps = new ArrayList();
// 通過map集成entrySet方法獲取entity
Set<entry> entrySet = paramMap.entrySet();
// 循環遍歷,獲取迭代器
Iterator<entry> iterator = entrySet.iterator();
while (iterator.hasNext()) {
EntrymapEntry = 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;
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
有時候我們在使用post請求時,可能傳入的參數是json或者其他格式,此時我們則需要更改請求頭及參數的設置信息,以httpClient4.5爲例,更改下面兩列配置:httpPost.setEntity(new StringEntity(“你的json串”)); httpPost.addHeader(“Content-Type”, “application/json”)。
實例:
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
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.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
static Log log = LogFactory.getLog(HttpClientUtils.class);
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(100);
httpClient = HttpClients.custom().setRetryHandler(createRequestRetryHandler()).setConnectionManager(cm).build();
}
private static RequestConfig getRequestConfig() {
// return
// RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
return RequestConfig.custom().setConnectTimeout(120000).setConnectionRequestTimeout(120000)
.setSocketTimeout(120000).build();
}
private static HttpRequestRetryHandler createRequestRetryHandler() {
return new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount > 3) {
return false;
}
if (exception instanceof InterruptedIOException || exception instanceof UnknownHostException
|| exception instanceof ConnectTimeoutException || exception instanceof SSLException) {
return false;
}
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
return true;
}
return false;
}
};
}
/**
* 無參get請求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doGet(String url) throws Exception {
// 創建http GET請求
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(getRequestConfig());// 設置請求參數
CloseableHttpResponse response = null;
try {
long begin = System.currentTimeMillis();
// 執行請求鄭州 不 孕 不 育 醫 院:http://jbk.39.net/yiyuanzaixian/zztjyy/
response = httpClient.execute(httpGet);
long end = System.currentTimeMillis();
long timeLength = (end - begin) / 1000;
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
log.info("時長: " + timeLength + "s, URL: " + url);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
log.info("時長: " + timeLength + "s, 異常URL: " + url);
throw new BusinessException("查詢數據爲空");
}
} catch (Exception ex) {
throw ex;
} finally {
if (response != null) {
response.close();
}
}
}
/**
* 有參get請求
*
* @param url
* @return
* @throws URISyntaxException
* @throws IOException
* @throws ClientProtocolException
*/
public static String doGet(String url, Mapparams) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
for (String key : params.keySet()) {
uriBuilder.setParameter(key, params.get(key));
}
}
return doGet(uriBuilder.build().toString());
}
/**
* 有參post請求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPost(String url, Mapparams) throws Exception {
// 創建http POST請求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if (params != null) {
// 設置2個post參數,一個是scope、一個是q
Listparameters = new ArrayList(0);
for (String key : params.keySet()) {
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 構造一個form表單式的實體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
// 將請求實體設置到httpPost對象中
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
// 執行請求
response = httpClient.execute(httpPost);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 有參post請求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPost(String url, Mapparams, MapheaderMap)
throws Exception {
// 創建http POST請求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if(headerMap != null){
for(Entryheader: headerMap.entrySet()){
httpPost.setHeader(header.getKey(), header.getValue());
}
}
if (params != null) {
// 設置2個post參數,一個是scope、一個是q
Listparameters = new ArrayList(0);
for (String key : params.keySet()) {
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 構造一個form表單式的實體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
// 將請求實體設置到httpPost對象中
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
// 執行請求
response = httpClient.execute(httpPost);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 有參post請求所傳參數爲文件
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPostMultipartFile(String url, Mapparams, MapheaderMap)
throws Exception {
// 創建http POST請求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if(headerMap != null){
for(Entryheader: headerMap.entrySet()){
httpPost.setHeader(header.getKey(), header.getValue());
}
}
if (params != null) {
// 構造一個form表單式的實體
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (String key : params.keySet()) {
builder.addBinaryBody(key, new File(params.get(key)));
}
HttpEntity reqEntity = builder.build();
// 將請求實體設置到httpPost對象中
httpPost.setEntity(reqEntity);
}
CloseableHttpResponse response = null;
try {
// 執行請求
response = httpClient.execute(httpPost);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 有參post請求,json交互
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPostJson(String url, String json) throws Exception {
// 創建http POST請求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if (StringUtils.isNotBlank(json)) {
// 標識出傳遞的參數是 application/json
StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse response = null;
try {
// 執行請求
response = httpClient.execute(httpPost);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 無參post請求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPost(String url) throws Exception {
return doPost(url, null);
}
}