liuxiaolong
2019-05-09 0d1d88cdb668e75ea8609417ac18ae19947e9525
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package com.basic.easemob;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.core.MediaType;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
 
/**
 * 用于环信IM的HTT    P组件
 * 
 * @company 北京贝思科技术有限公司
 * @author liuyajun, 8384503@qq.com
 * @date 2016年1月25日
 * @time 下午12:52:28
 */
public class HttpUtil {
 
    /** METHOD_DELETE value:GET */
    public static String METHOD_GET = "GET";
 
    /** METHOD_DELETE value:POST */
    public static String METHOD_POST = "POST";
 
    /** METHOD_DELETE value:PUT */
    public static String METHOD_PUT = "PUT";
 
    /** METHOD_DELETE value:DELETE */
    public static String METHOD_DELETE = "DELETE";
    
    public static String CONTENT_TYPE_JSON = "application/json";
 
    private static final Logger logger = Logger.getLogger(HttpUtil.class);
 
    /**
     * post, token, application/json
     * @param urlPath 以 /开头的相对url,前缀已经完成
     * @param data
     * @return
     */
    public static JSONObject sendRequest(String urlPath, JSONObject data){
        return sendRequest(IMConfig.getURL(urlPath), METHOD_POST, data, 
                IMConfig.getToken());
    }
    
    public static JSONObject sendRequest(String urlPath, String method, 
            JSONObject data){
        return sendRequest(IMConfig.getURL(urlPath), method, data, 
                IMConfig.getToken());
    }
 
    /**
     * Send SSL Request
     * 
     * @param url
     * @param method
     * @param data
     * @return
     */
    public static JSONObject sendRequest(URL url, String method, 
            JSONObject reqJson, String token) {
 
        HttpClient httpClient = getClient(true);
 
        JSONObject json = null;
 
        String contentType = CONTENT_TYPE_JSON;
        
        String data = "";
        if(reqJson !=null){
            data = reqJson.toString();
        }
        
        try {
            logger.info("send request: "+data);
            
            HttpResponse response = null;
 
            if (method.equals(METHOD_PUT)) {
                HttpPut httpPut = new HttpPut(url.toURI());
                if (token != null && token.trim().length() > 0) {
                    httpPut.addHeader("Authorization", "Bearer " + token.toString());
                }
                if(contentType !=null && contentType.trim().length()>0){
                    httpPut.addHeader("Content-Type", contentType);
                }
                
                if(data !=null && data.trim().length()>0){                    
                    httpPut.setEntity(new StringEntity(data, IMConfig.ENCODING));
                }
 
                response = httpClient.execute(httpPut);
            } else if (method.equals(METHOD_GET)) {
 
                HttpGet httpGet = new HttpGet(url.toURI());
                if (token != null && token.trim().length() > 0) {
                    httpGet.addHeader("Authorization", "Bearer " + token.toString());
                }
                if(contentType !=null && contentType.trim().length()>0){
                    httpGet.addHeader("Content-Type", contentType);
                }
                response = httpClient.execute(httpGet);
 
            } else if (method.equals(METHOD_DELETE)) {
                HttpDelete httpDelete = new HttpDelete(url.toURI());
                if (token != null && token.trim().length() > 0) {
                    httpDelete.addHeader("Authorization", "Bearer " + token.toString());
                }
                if(contentType !=null && contentType.trim().length()>0){
                    httpDelete.addHeader("Content-Type", contentType);
                }
                response = httpClient.execute(httpDelete);
                
            }else{    
                //默认post
                HttpPost httpPost = new HttpPost(url.toURI());
                
                if (token != null && token.trim().length() > 0) {
                    httpPost.addHeader("Authorization", "Bearer " + token.toString());
                }
                if(contentType !=null && contentType.trim().length()>0){
                    httpPost.addHeader("Content-Type", contentType);
                }
                
                if(data !=null && data.trim().length()>0){
                    httpPost.setEntity(new StringEntity(data, IMConfig.ENCODING));
                }
 
                response = httpClient.execute(httpPost);
            }
 
            HttpEntity entity = response.getEntity();
            
            if (null != entity) {
                String responseContent = EntityUtils.toString(entity, IMConfig.ENCODING);
                logger.info("response result: ("
                        +response.getStatusLine().getStatusCode()
                        +")\n"+responseContent);
                
                try{
                    json = new JSONObject(responseContent);
                    json.put("statusCode", response.getStatusLine().getStatusCode()+"");
                }catch(Throwable t){
                    throw t;
                }
            }
        } catch (Throwable e) {
            throw new RuntimeException("发送请求错误", e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
 
        return json;
    }
 
    /**
     * DownLoadFile with Jersey
     * @param url
     * @param headers
     * @param localPath
     * @param token
     * @return
     */
    public static File downLoadFile(URL url, 
            List<NameValuePair> headers, File localPath,
            String token) {
 
        HttpClient httpClient = getClient(true);
 
        try {
 
            HttpGet httpGet = new HttpGet(url.toURI());
 
            if (token != null && token.trim().length() > 0) {
                httpGet.addHeader("Authorization", "Bearer " + token.toString());
            }
            for (NameValuePair header : headers) {
                httpGet.addHeader(header.getName(), header.getValue());
            }
 
            HttpResponse response = httpClient.execute(httpGet);
 
            HttpEntity entity = response.getEntity();
            InputStream in = entity.getContent();
            FileOutputStream fos = new FileOutputStream(localPath);
 
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
 
            fos.close();
 
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
 
        return localPath;
    }
 
    /**
     * UploadFile whit Jersey
     * 
     * @return
     */
    public static JSONObject uploadFile(URL url, File file, 
            List<NameValuePair> headers, String token)
            throws RuntimeException {
        HttpClient httpClient = getClient(true);
 
        JSONObject json = null;
 
        try {
            HttpPost httpPost = new HttpPost(url.toURI());
 
            if (token != null && token.trim().length() > 0) {
                httpPost.addHeader("Authorization", "Bearer " + token.toString());
            }
            for (NameValuePair header : headers) {
                httpPost.addHeader(header.getName(), header.getValue());
            }
 
            MultipartEntity mpEntity = new MultipartEntity();
            ContentBody cbFile = new FileBody(file, MediaType.APPLICATION_OCTET_STREAM);
            mpEntity.addPart("file", cbFile);
            httpPost.setEntity(mpEntity);
 
            HttpResponse response = httpClient.execute(httpPost);
 
            HttpEntity entity = response.getEntity();
 
            if (null != entity) {
                String responseContent = EntityUtils.toString(entity, IMConfig.ENCODING);
                
                logger.info(responseContent);
                
                json = new JSONObject(responseContent);
            }
        } catch (Throwable e) {
            throw new RuntimeException();
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
 
        return json;
    }
 
    /**
     * Create a httpClient instance
     * 
     * @param isSSL
     * @return HttpClient instance
     */
    protected static HttpClient getClient(boolean isSSL) {
 
        HttpClient httpClient = new DefaultHttpClient();
        if (isSSL) {
            X509TrustManager xtm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
 
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
 
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
 
            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
 
                ctx.init(null, new TrustManager[] { xtm }, null);
 
                SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
 
                httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
 
            } catch (Throwable e) {
                throw new RuntimeException();
            }
        }
 
        return httpClient;
    }
 
}