郑永安
2023-06-19 f65443d8abeaedc9d102324565e8368e7c9d90c8
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package com.gk.firework.Domain.Utils;
 
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
 
public class HttpUtils {
    private static final Logger logger = LogManager.getLogger(HttpUtils.class);
 
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29";
    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
 
    //将map型转为请求参数型
    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
 
    //post json
//    public static String sendPost(String url, String data) {
//        String response = null;
//        try {
//            HttpClient httpclient = null;
//            HttpResponse httpresponse = null;
//            HttpPost httppost = null;
//
//            try {
//                httpclient = HttpClients.createDefault();
//                httppost = new HttpPost(url);
//                StringEntity stringentity = new StringEntity(data,
//                        ContentType.create("application/json", "UTF-8"));
//                httppost.setEntity(stringentity);
//                httpresponse = httpclient.execute(httppost);
//                response = EntityUtils
//                        .toString(httpresponse.getEntity());
//                // 检验返回码
//                 int statusCode = httpresponse.getStatusLine().getStatusCode();
//                 if(statusCode != HttpStatus.SC_OK){
//                     logger.error("请求出错: "+statusCode);
//                     if (statusCode == 307) {
//                         Header header = httpresponse.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD上
//                         String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请
//                         logger.error(newuri);
//
//                         httppost = new HttpPost(newuri);
//                         StringEntity newstringentity = new StringEntity(data,
//                                 ContentType.create("application/json", "UTF-8"));
//                         httppost.setEntity(newstringentity);
//                         httpresponse = httpclient.execute(httppost);
//                         response = EntityUtils
//                                 .toString(httpresponse.getEntity());
//
//                         logger.error("请求出错: "+httpresponse.getStatusLine().getStatusCode());
//                     }
//
//                 }
//            } catch (Exception e){
//                e.printStackTrace();
//            }finally {
//                if(httppost != null){
//                try {
//                    httppost.releaseConnection();
//                    Thread.sleep(500);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return response;
//    }
 
    public static String sendPost(String url, String data) {
        String resData = null;
        try {
            RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();//不允许重定向
            CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
 
//            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity se = new StringEntity(data, "UTF-8");
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            post.setEntity(se);
            CloseableHttpResponse response = client.execute(post);
            resData = EntityUtils.toString(response.getEntity());
            // 检验返回码
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode != HttpStatus.SC_OK){
                logger.error("请求出错: "+statusCode);
                if (statusCode == 307) {
                    Header header = response.getFirstHeader("Location"); // 跳转的目标地址是在 HTTP-HEAD上
                    String newuri = header.getValue(); // 这就是跳转后的地址,再向这个地址发出新申请
                    logger.error(newuri);
 
                    post = new HttpPost(newuri);
                    StringEntity newstringentity = new StringEntity(data,
                            ContentType.create("application/json", "UTF-8"));
                    post.setEntity(newstringentity);
                    response = client.execute(post);
                    resData = EntityUtils.toString(response.getEntity());
                    logger.error("请求出错: "+response.getStatusLine().getStatusCode());
                }
            }
            client.close();
            logger.info(resData);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return resData;
    }
 
 
}