httpclient https请求

本文介绍了一种使用Java实现HTTPS POST请求的方法,通过自定义信任管理器绕过证书验证,并展示了如何将参数转换为URL编码形式。



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
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;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class HttpUtil {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtil.class);

public static DefaultHttpClient getHttpsClient()
{
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {

@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}

@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}

};
DefaultHttpClient client = new DefaultHttpClient();
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);

ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
//设置要使用的端口,默认是443
sr.register(new Scheme("https", 443, ssf));
return client;
} catch (Exception ex) {
LOG.error("", ex);
return null;
}
}

/**
*
* @param url
* @param params
* @return
* @author asflex
* @date 2014-3-28下午7:24:02 
* @modify 2014-3-28下午7:24:02
*/
public static String post(String url, Map<String, String> params) {
DefaultHttpClient httpClient = getHttpsClient();
HttpPost post = new HttpPost(url);
HttpEntity entity = map2UrlEncodedFormEntity(params);
if(entity != null) {
post.setEntity(entity);
}
LOG.info("http post---{}", getUrlRequestInfo(url, params));
HttpResponse response;
try {
response = httpClient.execute(post);
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (ClientProtocolException e) {
LOG.error("", e);
} catch (IOException e) {
LOG.error("", e);
} finally {
httpClient.getConnectionManager().shutdown();
}
return null;
}

/**
* 生成post请求时的记录
* @param url
* @param params
* @return
* @author asflex
* @date 2014-3-28下午7:23:33 
* @modify 2014-3-28下午7:23:33
*/
public static String getUrlRequestInfo(String url, Map<String, String> params) {

StringBuilder paramStr = new StringBuilder();
if(MapUtils.isNotEmpty(params)) {
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
Joiner.on("&").appendTo(paramStr, iterator);
}
return String.format("curl -d '%s' '%s'", StringUtils.trimToEmpty(paramStr.toString()), StringUtils.trimToEmpty(url));
}
/**
* 参数转换
* @param params
* @return
* @author asflex
* @date 2014-3-28下午7:23:05 
* @modify 2014-3-28下午7:23:05
*/
public static HttpEntity map2UrlEncodedFormEntity(Map<String, String> params) {
if(MapUtils.isNotEmpty(params)) {
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
List<NameValuePair> nvps = Lists.newArrayList();
while(iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
nvps.add(new BasicNameValuePair(StringUtils.trimToEmpty(entry.getKey()), StringUtils.trimToEmpty(entry.getValue())));
}
try {
return new UrlEncodedFormEntity(nvps);
} catch (UnsupportedEncodingException e) {
LOG.error("", e);
}
}
return null;
}

public static void main(String[] args) {
Map<String, String> params = Maps.newHashMapWithExpectedSize(8);
params.put("username", "fred5");
params.put("password", "1111");
params.put("vcode", "");
System.out.println(getUrlRequestInfo("", params));
System.out.println(post("https://www.baidu.com/webApi/logins.jsp", params));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值