需要先引入工具类httpclient-4.5.jar,httpcore-4.4.6.jar
//--------------------------------------------------------------------------
package com.paifenle.risk.drools.util.comment;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Dabria_ly 2017年6月29日
*/
public class HttpClientUtil {
private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
// 默认的数据返回超时时间
private static final int defaultWaitingTimeOut = 60000;
// 默认的连接超时时间
private static final int defaultTimeOut = 60000;
public static void main(String[] args) {
Map
params.put("userId", "50073111");
String str = HttpClientUtil.doPost("http://xxx.xx.x.xx:8080/Lendon/selectLendonScore", params, "UTF-8");
System.out.println(String.format("str=%s", str));
String url = new StringBuilder().append("http://xxx.xx.x.xx:8080/UserMix/getUserMix")
.append("?userId=").append("50073111")
.append("¤tId=").append("1000000901")
.toString();
String result = HttpClientUtil.doGet(url, "UTF-8");
System.out.println(String.format("result=%s", result));
}
/**
* http post
* @param url
* @param map
* @param charset
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String doPost(String url, Map
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
// 设置参数
List
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* http get 请求
*
* @param url
* @param charset
* @param timeout
* @return
*/
public static String doGet(String url, String charset, int timeout) {
LOG.info("http get: url:{}", url);
String returnStr = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(defaultWaitingTimeOut) // 设置数据等待时间
.setConnectTimeout(timeout) // 设置连接超时时间
.build();
// 设置请求地址
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse httpResponse = null;
try {
httpGet.setConfig(requestConfig);
// 设置HttpPost数据
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
returnStr = EntityUtils.toString(httpEntity, charset);
}
}
} catch (Exception e) {
LOG.error("httpGet 异常" + e);
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
LOG.error("httpGet 连接关闭异常" + e);
}
}
}
return returnStr;
}
/**
* http get 请求
*
* @param url
* @param charset
* @return
*/
public static String doGet(String url, String charset) {
return doGet(url, charset, defaultTimeOut);
}
/**
* 文件上传方式请求--OCR
* @param url:请求路径
* @param map:请求参数
* @param image:文件全名
* @param charset:字符集设置(UTF-8)
* @return
*/
public String doUpload(String url,Map
String result = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
// httpClient = HttpClients.createDefault();
httpClient = new SSLClient();
// 把一个普通参数和文件上传给下面这个地址 是一个servlet
HttpPost httpPost = new HttpPost(url);
// 把文件转换成流对象FileBody
FileBody bin = null;
// URL mURL = new URL(image);
try {
// File fi = new File("http://obojjnevn.bkt.clouddn.com"+File.separator+mURL.getFile());
//File fi = new File("E:/img/10032016082619152300000.jpg");
bin = new FileBody(new File(image));
} catch (Exception e) {
e.printStackTrace();
}
//FileBody bin = new FileBody(image);
StringBody api_key = new StringBody(map.get("api_key").toString(), ContentType.create(
"text/plain", Consts.UTF_8));
StringBody password = new StringBody(map.get("api_secret").toString(), ContentType.create(
"text/plain", Consts.UTF_8));
HttpEntity reqEntity = MultipartEntityBuilder.create()
// 相当于
.addPart("image", bin)
// 相当于
.addPart("api_key", api_key)
.addPart("api_secret", password)
.build();
httpPost.setEntity(reqEntity);
// 发起请求 并返回请求的响应
response = httpClient.execute(httpPost);
LOG.info("The response value of token--->" + response.getFirstHeader("token"));
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result =EntityUtils.toString(resEntity,charset);
// 打印响应长度
LOG.info("Response content length---> " + resEntity.getContentLength());
// 打印响应内容
// System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
LOG.info("Response content--->" +result);
}
// 销毁
EntityUtils.consume(resEntity);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(response != null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(httpClient != null){
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
//----------------------------------------------------------------------------------------------
package com.paifenle.risk.drools.util.comment;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
/**
*
* @author Dabria_ly 2017年6月29日
*/
public class SSLClient extends DefaultHttpClient{
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}}