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;
|
}
|
|
}
|