Blame view

src/main/java/com/huaheng/common/utils/http/HttpUtils.java 12.8 KB
tangying authored
1
2
package com.huaheng.common.utils.http;
3
import com.huaheng.common.utils.StringUtils;
周峰 authored
4
5
6
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import org.apache.commons.io.IOUtils;
mahuandong authored
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;
tangying authored
13
14
15
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
mahuandong authored
16
17
import javax.net.ssl.*;
import java.io.*;
周鸿 authored
18
import java.math.BigDecimal;
mahuandong authored
19
20
21
import java.net.*;
import java.security.cert.X509Certificate;
tangying authored
22
23
24

/**
 * 通用http发送方法
25
 *
tangying authored
26
27
 * @author huaheng
 */
28
public class HttpUtils {
tangying authored
29
30
31
32
33
34

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
35
     * @param url   发送请求的 URL
tangying authored
36
37
38
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
39
    public static String sendGet(String url, String param) {
tangying authored
40
41
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
42
        try {
tangying authored
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) {
tangying authored
54
55
56
                result.append(line);
            }
            log.info("recv - {}", result);
57
        } catch (ConnectException e) {
tangying authored
58
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e.getMessage());
59
        } catch (SocketTimeoutException e) {
tangying authored
60
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
61
        } catch (IOException e) {
tangying authored
62
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e.getMessage());
63
        } catch (Exception e) {
tangying authored
64
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e.getMessage());
65
66
67
        } finally {
            try {
                if (in != null) {
tangying authored
68
69
                    in.close();
                }
70
            } catch (Exception ex) {
tangying authored
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
tangying authored
81
82
83
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
84
    public static String sendPost(String url, String param) {
tangying authored
85
86
87
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
88
        try {
tangying authored
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) {
mahuandong authored
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"));
tangying authored
109
            String line;
110
            while ((line = in.readLine()) != null) {
tangying authored
111
112
113
                result.append(line);
            }
            log.info("recv - {}", result);
114
        } catch (ConnectException e) {
tangying authored
115
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
116
        } catch (SocketTimeoutException e) {
tangying authored
117
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
118
        } catch (IOException e) {
tangying authored
119
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e.getMessage());
120
        } catch (Exception e) {
tangying authored
121
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e.getMessage());
122
123
124
        } finally {
            try {
                if (out != null) {
tangying authored
125
126
                    out.close();
                }
127
                if (in != null) {
tangying authored
128
129
                    in.close();
                }
130
            } catch (IOException ex) {
tangying authored
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) {
tangying authored
138
139
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
140
        try {
tangying authored
141
142
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
143
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
tangying authored
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())) {
tangying authored
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) {
tangying authored
169
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e.getMessage());
170
        } catch (SocketTimeoutException e) {
tangying authored
171
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e.getMessage());
172
        } catch (IOException e) {
tangying authored
173
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e.getMessage());
174
        } catch (Exception e) {
tangying authored
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) {
tangying authored
188
189
        System.out.println(strURL);
        System.out.println(params);
周峰 authored
190
191
192
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStreamWriter out = null;
tangying authored
193
        String result = null;
周峰 authored
194
195
        ApiLog log = null;
tangying authored
196
197
        try {
            URL url = new URL(strURL);// 创建连接
周峰 authored
198
            connection = (HttpURLConnection) url.openConnection();
tangying authored
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");// 设置发送数据的格式
游杰 authored
206
207
208
209
210
211
            if (StringUtils.isEmpty(apiName)) {
                log = ApiLogAspect.initApiLog(connection, params);
            } else {
                log = ApiLogAspect.initApiLog(connection, params, apiName);
            }
周峰 authored
212
            connection.connect();
213
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");// utf-8编码
游杰 authored
214
215
216
            out.append(params);
            out.flush();
            out.close(); // 读取响应
tangying authored
217
            int length = (int) connection.getContentLength();// 获取长度
周峰 authored
218
            is = connection.getInputStream();
tangying authored
219
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
游杰 authored
220
            length = 10000;
221
            if (length > 0) {
tangying authored
222
223
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
游杰 authored
224
225
226
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
tangying authored
227
228
229
230
231
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                result = new String(data, "UTF-8");
                System.out.println(result);
游杰 authored
232
            }
tangying authored
233
        } catch (Exception e) {
周峰 authored
234
            ApiLogAspect.setApiLogException(log, e);
tangying authored
235
            e.printStackTrace();
236
        } finally {
周峰 authored
237
            ApiLogAspect.finishApiLog(log, connection, result);
238
            if (connection != null) {
周峰 authored
239
                connection.disconnect();
240
            }
周峰 authored
241
            IOUtils.closeQuietly(out, is);
tangying authored
242
243
244
245
        }
        return result;
    }
mahuandong authored
246
247
    /**
     * 发送以json为参数的POST请求
248
     *
mahuandong authored
249
250
251
252
     * @param json
     * @param url
     * @return
     */
253
    public static String sendJsonPostToken(String json, String url) {
mahuandong authored
254
255
        String result = "";
        HttpPost post = new HttpPost(url);
256
        try {
mahuandong authored
257
258
            CloseableHttpClient httpClient = HttpClients.createDefault();
259
            post.setHeader("Content-Type", "application/json;charset=utf-8");
mahuandong authored
260
            post.addHeader("Authorization", "Basic YWRtaW46");
261
            StringEntity postingString = new StringEntity(json, "utf-8");
mahuandong authored
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();
mahuandong authored
268
            String line = null;
269
270
            while ((line = br.readLine()) != null) {
                strber.append(line + '\n');
mahuandong authored
271
272
273
274
            }
            br.close();
            in.close();
            result = strber.toString();
275
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
mahuandong authored
276
277
                result = "服务器异常";
            }
278
        } catch (Exception e) {
mahuandong authored
279
280
            System.out.println("请求异常");
            throw new RuntimeException(e);
281
        } finally {
mahuandong authored
282
283
284
285
            post.abort();
        }
        return result;
    }
tangying authored
286
287
    private static class TrustAnyTrustManager implements X509TrustManager {
tangying authored
288
        @Override
289
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
tangying authored
290
291
292
        }

        @Override
293
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
tangying authored
294
295
296
        }

        @Override
297
298
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
tangying authored
299
300
301
        }
    }
302
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
tangying authored
303
        @Override
304
        public boolean verify(String hostname, SSLSession session) {
tangying authored
305
306
307
308
            return true;
        }
    }
周鸿 authored
309
    public static void main(String[] args) {
310
311
        String str = "000002.5";
        BigDecimal bigDecimal = new BigDecimal(str);
周鸿 authored
312
313
314
        System.out.println(bigDecimal);
    }
315
}