目前JAVA實(shí)現(xiàn)HTTP請(qǐng)求的方法用的最多的有兩種:一種是通過HTTPClient這種第三方的開源框架去實(shí)現(xiàn)。HTTPClient對(duì)HTTP的封裝性比較不錯(cuò),通過它基本上能夠滿足我們大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作遠(yuǎn)程 url的工具包,雖然已不再更新,但實(shí)現(xiàn)工作中使用httpClient3.1的代碼還是很多,HttpClient4.5是org.apache.http.client下操作遠(yuǎn)程 url的工具包,最新的;另一種則是通過HttpURLConnection去實(shí)現(xiàn),HttpURLConnection是JAVA的標(biāo)準(zhǔn)類,是JAVA比較原生的一種實(shí)現(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連接對(duì)象
URL url = new URL(httpurl);
// 通過遠(yuǎn)程url連接對(duì)象打開一個(gè)連接,強(qiáng)轉(zhuǎn)成httpURLConnection類
connection = (HttpURLConnection) url.openConnection();
// 設(shè)置連接方式:get
connection.setRequestMethod("GET");
// 設(shè)置連接主機(jī)服務(wù)器的超時(shí)時(shí)間:15000毫秒
connection.setConnectTimeout(15000);
// 設(shè)置讀取遠(yuǎn)程返回的數(shù)據(jù)時(shí)間:60000毫秒
connection.setReadTimeout(60000);
// 發(fā)送請(qǐng)求
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連接對(duì)象打開連接
connection = (HttpURLConnection) url.openConnection();
// 設(shè)置連接請(qǐng)求方式
connection.setRequestMethod("POST");
// 設(shè)置連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
connection.setConnectTimeout(15000);
// 設(shè)置讀取主機(jī)服務(wù)器返回?cái)?shù)據(jù)超時(shí)時(shí)間:60000毫秒
connection.setReadTimeout(60000);
// 默認(rèn)值為:false,當(dāng)向遠(yuǎn)程服務(wù)器傳送數(shù)據(jù)/寫數(shù)據(jù)時(shí),需要設(shè)置為true
connection.setDoOutput(true);
// 默認(rèn)值為:true,當(dāng)前向遠(yuǎn)程服務(wù)讀取數(shù)據(jù)時(shí),設(shè)置為true,該參數(shù)可有可無
connection.setDoInput(true);
// 設(shè)置傳入?yún)?shù)的格式:請(qǐng)求參數(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-ee040be542c0
connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 通過連接對(duì)象獲取一個(gè)輸出流
os = connection.getOutputStream();
// 通過輸出流對(duì)象將參數(shù)寫出去/傳輸出去,它是通過字節(jié)數(shù)組寫出的
os.write(param.getBytes());
// 通過連接對(duì)象獲取一個(gè)輸入流,向遠(yuǎn)程讀取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 對(duì)輸入流對(duì)象進(jìn)行包裝:charset根據(jù)工作項(xiàng)目組的要求來設(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;
}
}
-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
-
145
-
146
-
147
-
148
-
149
-
150
-
151
第二種方式: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實(shí)例
HttpClient httpClient = new HttpClient();
// 設(shè)置http連接主機(jī)服務(wù)超時(shí)時(shí)間:15000毫秒
// 先獲取連接管理器對(duì)象,再獲取參數(shù)對(duì)象,再進(jìn)行參數(shù)的賦值
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 創(chuàng)建一個(gè)Get方法實(shí)例對(duì)象
GetMethod getMethod = new GetMethod(url);
// 設(shè)置get請(qǐng)求超時(shí)為60000毫秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
// 設(shè)置請(qǐng)求重試機(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,說明失敗了,打印錯(cuò)誤信息
System.err.println("Method faild: " + getMethod.getStatusLine());
} else {
// 通過getMethod實(shí)例,獲取遠(yuǎn)程的一個(gè)輸入流
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實(shí)例對(duì)象
HttpClient httpClient = new HttpClient();
// 設(shè)置httpClient連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 創(chuàng)建post請(qǐng)求方法實(shí)例對(duì)象
PostMethod postMethod = new PostMethod(url);
// 設(shè)置post請(qǐng)求超時(shí)時(shí)間
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
NameValuePair[] nvp = null;
// 判斷參數(shù)map集合paramMap是否為空
if (null != paramMap && paramMap.size() > 0) {// 不為空
// 創(chuàng)建鍵值參數(shù)對(duì)象數(shù)組,大小為參數(shù)的個(gè)數(shù)
nvp = new NameValuePair[paramMap.size()];
// 循環(huán)遍歷參數(shù)集合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創(chuàng)建鍵值對(duì)象存放到數(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對(duì)象中
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;
}
}
-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
-
145
-
146
-
147
-
148
-
149
-
150
-
151
-
152
-
153
-
154
-
155
-
156
-
157
-
158
-
159
-
160
-
161
-
162
-
163
-
164
-
165
-
166
-
167
-
168
-
169
-
170
第三種方式: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)建一個(gè)httpClient實(shí)例
httpClient = HttpClients.createDefault();
// 創(chuàng)建httpGet遠(yuǎn)程連接實(shí)例
HttpGet httpGet = new HttpGet(url);
// 設(shè)置請(qǐng)求頭信息,鑒權(quán)
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
// 設(shè)置配置請(qǐng)求參數(shù)
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 連接主機(jī)服務(wù)超時(shí)時(shí)間
.setConnectionRequestTimeout(35000)// 請(qǐng)求超時(shí)時(shí)間
.setSocketTimeout(60000)// 數(shù)據(jù)讀取超時(shí)時(shí)間
.build();
// 為httpGet實(shí)例設(shè)置配置
httpGet.setConfig(requestConfig);
// 執(zhí)行g(shù)et請(qǐng)求得到返回對(duì)象
response = httpClient.execute(httpGet);
// 通過返回對(duì)象獲取返回?cái)?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實(shí)例
httpClient = HttpClients.createDefault();
// 創(chuàng)建httpPost遠(yuǎn)程連接實(shí)例
HttpPost httpPost = new HttpPost(url);
// 配置請(qǐng)求參數(shù)實(shí)例
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設(shè)置連接主機(jī)服務(wù)超時(shí)時(shí)間
.setConnectionRequestTimeout(35000)// 設(shè)置連接請(qǐng)求超時(shí)時(shí)間
.setSocketTimeout(60000)// 設(shè)置讀取數(shù)據(jù)連接超時(shí)時(shí)間
.build();
// 為httpPost實(shí)例設(shè)置配置
httpPost.setConfig(requestConfig);
// 設(shè)置請(qǐng)求頭
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// 封裝post請(qǐng)求參數(shù)
if (null != paramMap && paramMap.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// 通過map集成entrySet方法獲取entity
Set<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è)置封裝好的請(qǐng)求參數(shù)
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
try {
// httpClient對(duì)象執(zhí)行post請(qǐng)求,并返回響應(yīng)參數(shù)對(duì)象
httpResponse = httpClient.execute(httpPost);
// 從響應(yīng)對(duì)象中獲取響應(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;
}
}
-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
-
106
-
107
-
108
-
109
-
110
-
111
-
112
-
113
-
114
-
115
-
116
-
117
-
118
-
119
-
120
-
121
-
122
-
123
-
124
-
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
有時(shí)候我們?cè)谑褂胮ost請(qǐng)求時(shí),可能傳入的參數(shù)是json或者其他格式,此時(shí)我們則需要更改請(qǐng)求頭及參數(shù)的設(shè)置信息,以httpClient4.5為例,更改下面兩列配置:httpPost.setEntity(new StringEntity(“你的json串”)); httpPost.addHeader(“Content-Type”, “application/json”)。
實(shí)例:
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請(qǐng)求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doGet(String url) throws Exception {
// 創(chuàng)建http GET請(qǐng)求
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(getRequestConfig());// 設(shè)置請(qǐng)求參數(shù)
CloseableHttpResponse response = null;
try {
long begin = System.currentTimeMillis();
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpGet);
long end = System.currentTimeMillis();
long timeLength = (end - begin) / 1000;
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
log.info("時(shí)長: " + timeLength + "s, URL: " + url);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
log.info("時(shí)長: " + timeLength + "s, 異常URL: " + url);
throw new BusinessException("查詢數(shù)據(jù)為空");
}
} catch (Exception ex) {
throw ex;
} finally {
if (response != null) {
response.close();
}
}
}
/**
* 有參get請(qǐng)求
*
* @param url
* @return
* @throws URISyntaxException
* @throws IOException
* @throws ClientProtocolException
*/
public static String doGet(String url, Map<String, String> params) 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請(qǐng)求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPost(String url, Map<String, String> params) throws Exception {
// 創(chuàng)建http POST請(qǐng)求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if (params != null) {
// 設(shè)置2個(gè)post參數(shù),一個(gè)是scope、一個(gè)是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for (String key : params.keySet()) {
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 構(gòu)造一個(gè)form表單式的實(shí)體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
// 將請(qǐng)求實(shí)體設(shè)置到httpPost對(duì)象中
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpPost);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 有參post請(qǐng)求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPost(String url, Map<String, String> params, Map<String, String> headerMap)
throws Exception {
// 創(chuàng)建http POST請(qǐng)求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if(headerMap != null){
for(Entry<String, String> header: headerMap.entrySet()){
httpPost.setHeader(header.getKey(), header.getValue());
}
}
if (params != null) {
// 設(shè)置2個(gè)post參數(shù),一個(gè)是scope、一個(gè)是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
for (String key : params.keySet()) {
parameters.add(new BasicNameValuePair(key, params.get(key)));
}
// 構(gòu)造一個(gè)form表單式的實(shí)體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
// 將請(qǐng)求實(shí)體設(shè)置到httpPost對(duì)象中
httpPost.setEntity(formEntity);
}
CloseableHttpResponse response = null;
try {
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpPost);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 有參post請(qǐng)求所傳參數(shù)為文件
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPostMultipartFile(String url, Map<String, String> params, Map<String, String> headerMap)
throws Exception {
// 創(chuàng)建http POST請(qǐng)求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if(headerMap != null){
for(Entry<String, String> header: headerMap.entrySet()){
httpPost.setHeader(header.getKey(), header.getValue());
}
}
if (params != null) {
// 構(gòu)造一個(gè)form表單式的實(shí)體
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (String key : params.keySet()) {
builder.addBinaryBody(key, new File(params.get(key)));
}
HttpEntity reqEntity = builder.build();
// 將請(qǐng)求實(shí)體設(shè)置到httpPost對(duì)象中
httpPost.setEntity(reqEntity);
}
CloseableHttpResponse response = null;
try {
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpPost);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 有參post請(qǐng)求,json交互
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPostJson(String url, String json) throws Exception {
// 創(chuàng)建http POST請(qǐng)求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getRequestConfig());
if (StringUtils.isNotBlank(json)) {
// 標(biāo)識(shí)出傳遞的參數(shù)是 application/json
StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse response = null;
try {
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpPost);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} finally {
if (response != null) {
response.close();
}
}
return null;
}
/**
* 無參post請(qǐng)求
*
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPost(String url) throws Exception {
return doPost(url, null);
}
}
本站文章版權(quán)歸原作者及原出處所有 。內(nèi)容為作者個(gè)人觀點(diǎn), 并不代表本站贊同其觀點(diǎn)和對(duì)其真實(shí)性負(fù)責(zé),本站只提供參考并不構(gòu)成任何投資及應(yīng)用建議。本站是一個(gè)個(gè)人學(xué)習(xí)交流的平臺(tái),網(wǎng)站上部分文章為轉(zhuǎn)載,并不用于任何商業(yè)目的,我們已經(jīng)盡可能的對(duì)作者和來源進(jìn)行了通告,但是能力有限或疏忽,造成漏登,請(qǐng)及時(shí)聯(lián)系我們,我們將根據(jù)著作權(quán)人的要求,立即更正或者刪除有關(guān)內(nèi)容。本站擁有對(duì)此聲明的最終解釋權(quán)。