|
1
2
|
package com.huaheng.common.utils.http;
|
|
3
|
import com.huaheng.common.utils.StringUtils;
|
|
4
5
6
|
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import org.apache.commons.io.IOUtils;
|
|
7
8
9
10
11
12
|
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpClients;
|
|
13
14
15
|
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
|
|
16
17
|
import javax.net.ssl.*;
import java.io.*;
|
|
18
|
import java.math.BigDecimal;
|
|
19
20
21
|
import java.net.*;
import java.security.cert.X509Certificate;
|
|
22
23
24
|
/**
* 通用http发送方法
|
|
25
|
*
|
|
26
27
|
* @author huaheng
*/
|
|
28
|
public class HttpUtils {
|
|
29
30
31
32
33
34
|
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 向指定 URL 发送GET方法的请求
*
|
|
35
|
* @param url 发送请求的 URL
|
|
36
37
38
|
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
|
|
39
|
public static String sendGet(String url, String param) {
|
|
40
41
|
StringBuilder result = new StringBuilder();
BufferedReader in = null;
|
|
42
|
try {
|
|
43
44
45
46
47
48
49
50
51
52
|
String urlNameString = url + "?" + param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
|
|
53
|
while ((line = in.readLine()) != null) {
|
|
54
55
56
|
result.append(line);
}
log.info("recv - {}", result);
|
|
57
|
} catch (ConnectException e) {
|
|
58
|
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e.getMessage());
|
|
59
|
} catch (SocketTimeoutException e) {
|
|
60
|
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
|
|
61
|
} catch (IOException e) {
|
|
62
|
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e.getMessage());
|
|
63
|
} catch (Exception e) {
|
|
64
|
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e.getMessage());
|
|
65
66
67
|
} finally {
try {
if (in != null) {
|
|
68
69
|
in.close();
}
|
|
70
|
} catch (Exception ex) {
|
|
71
72
73
74
75
76
77
78
79
|
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
|
|
80
|
* @param url 发送请求的 URL
|
|
81
82
83
|
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
|
|
84
|
public static String sendPost(String url, String param) {
|
|
85
86
87
|
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
|
|
88
|
try {
|
|
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
String urlNameString = url + "?" + param;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
|
|
103
|
if (((HttpURLConnection) conn).getResponseCode() >= 390) {
|
|
104
105
106
107
108
|
in = new BufferedReader(new InputStreamReader(((HttpURLConnection) conn).getErrorStream()));
} else {
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
// in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
|
|
109
|
String line;
|
|
110
|
while ((line = in.readLine()) != null) {
|
|
111
112
113
|
result.append(line);
}
log.info("recv - {}", result);
|
|
114
|
} catch (ConnectException e) {
|
|
115
|
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
|
|
116
|
} catch (SocketTimeoutException e) {
|
|
117
|
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
|
|
118
|
} catch (IOException e) {
|
|
119
|
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e.getMessage());
|
|
120
|
} catch (Exception e) {
|
|
121
|
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e.getMessage());
|
|
122
123
124
|
} finally {
try {
if (out != null) {
|
|
125
126
|
out.close();
}
|
|
127
|
if (in != null) {
|
|
128
129
|
in.close();
}
|
|
130
|
} catch (IOException ex) {
|
|
131
132
133
134
135
136
|
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex.getMessage());
}
}
return result.toString();
}
|
|
137
|
public static String sendSSLPost(String url, String param) {
|
|
138
139
|
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
|
|
140
|
try {
|
|
141
142
|
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
|
|
143
|
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
|
|
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
|
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
|
|
160
161
|
while ((ret = br.readLine()) != null) {
if (ret != null && !"".equals(ret.trim())) {
|
|
162
163
164
165
166
167
|
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
|
|
168
|
} catch (ConnectException e) {
|
|
169
|
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
|
|
170
|
} catch (SocketTimeoutException e) {
|
|
171
|
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
|
|
172
|
} catch (IOException e) {
|
|
173
|
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e.getMessage());
|
|
174
|
} catch (Exception e) {
|
|
175
176
177
178
179
180
181
|
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e.getMessage());
}
return result.toString();
}
//此方法是将参数以body形式发送post请求
|
|
182
|
public static String bodypost(String strURL, String params, String warehouseCode) {
|
|
183
184
185
186
187
|
return bodypost(strURL, params, warehouseCode, null);
}
//此方法是将参数以body形式发送post请求
public static String bodypost(String strURL, String params, String warehouseCode, String apiName) {
|
|
188
189
|
System.out.println(strURL);
System.out.println(params);
|
|
190
191
192
|
HttpURLConnection connection = null;
InputStream is = null;
OutputStreamWriter out = null;
|
|
193
|
String result = null;
|
|
194
195
|
ApiLog log = null;
|
|
196
197
|
try {
URL url = new URL(strURL);// 创建连接
|
|
198
|
connection = (HttpURLConnection) url.openConnection();
|
|
199
200
201
202
203
|
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");// 设置请求方式
|
|
204
205
|
connection.setRequestProperty("Accept", "application/json");// 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json");// 设置发送数据的格式
|
|
206
|
|
|
207
208
209
210
211
|
if (StringUtils.isEmpty(apiName)) {
log = ApiLogAspect.initApiLog(connection, params);
} else {
log = ApiLogAspect.initApiLog(connection, params, apiName);
}
|
|
212
|
connection.connect();
|
|
213
|
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");// utf-8编码
|
|
214
215
216
|
out.append(params);
out.flush();
out.close(); // 读取响应
|
|
217
|
int length = (int) connection.getContentLength();// 获取长度
|
|
218
|
is = connection.getInputStream();
|
|
219
|
BufferedReader br = new BufferedReader(new InputStreamReader(is));
|
|
220
|
length = 10000;
|
|
221
|
if (length > 0) {
|
|
222
223
|
byte[] data = new byte[length];
byte[] temp = new byte[512];
|
|
224
225
226
|
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
|
|
227
228
229
230
231
|
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
result = new String(data, "UTF-8");
System.out.println(result);
|
|
232
|
}
|
|
233
|
} catch (Exception e) {
|
|
234
|
ApiLogAspect.setApiLogException(log, e);
|
|
235
|
e.printStackTrace();
|
|
236
|
} finally {
|
|
237
|
ApiLogAspect.finishApiLog(log, connection, result);
|
|
238
|
if (connection != null) {
|
|
239
|
connection.disconnect();
|
|
240
|
}
|
|
241
|
IOUtils.closeQuietly(out, is);
|
|
242
243
244
245
|
}
return result;
}
|
|
246
247
|
/**
* 发送以json为参数的POST请求
|
|
248
|
*
|
|
249
250
251
252
|
* @param json
* @param url
* @return
*/
|
|
253
|
public static String sendJsonPostToken(String json, String url) {
|
|
254
255
|
String result = "";
HttpPost post = new HttpPost(url);
|
|
256
|
try {
|
|
257
258
|
CloseableHttpClient httpClient = HttpClients.createDefault();
|
|
259
|
post.setHeader("Content-Type", "application/json;charset=utf-8");
|
|
260
|
post.addHeader("Authorization", "Basic YWRtaW46");
|
|
261
|
StringEntity postingString = new StringEntity(json, "utf-8");
|
|
262
263
264
265
266
|
post.setEntity(postingString);
HttpResponse response = httpClient.execute(post);
InputStream in = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
|
|
267
|
StringBuilder strber = new StringBuilder();
|
|
268
|
String line = null;
|
|
269
270
|
while ((line = br.readLine()) != null) {
strber.append(line + '\n');
|
|
271
272
273
274
|
}
br.close();
in.close();
result = strber.toString();
|
|
275
|
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
|
|
276
277
|
result = "服务器异常";
}
|
|
278
|
} catch (Exception e) {
|
|
279
280
|
System.out.println("请求异常");
throw new RuntimeException(e);
|
|
281
|
} finally {
|
|
282
283
284
285
|
post.abort();
}
return result;
}
|
|
286
|
|
|
287
|
private static class TrustAnyTrustManager implements X509TrustManager {
|
|
288
|
@Override
|
|
289
|
public void checkClientTrusted(X509Certificate[] chain, String authType) {
|
|
290
291
292
|
}
@Override
|
|
293
|
public void checkServerTrusted(X509Certificate[] chain, String authType) {
|
|
294
295
296
|
}
@Override
|
|
297
298
|
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
|
|
299
300
301
|
}
}
|
|
302
|
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
|
|
303
|
@Override
|
|
304
|
public boolean verify(String hostname, SSLSession session) {
|
|
305
306
307
308
|
return true;
}
}
|
|
309
|
public static void main(String[] args) {
|
|
310
311
|
String str = "000002.5";
BigDecimal bigDecimal = new BigDecimal(str);
|
|
312
313
314
|
System.out.println(bigDecimal);
}
|
|
315
|
}
|