Java-利用HttpClient进行https访问

本文介绍如何通过HttpClient进行https访问。

下载并导入httpClient

下载httpClient,并将jar包导入到项目中

创建SSLClient类

创建SSLClient类,继承DefaultHttpClient,负责创建SSL连接:

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

}

Get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static String doGet(String url, String params){
HttpClient httpClient = null;
HttpGet httpGet = null;
String result = null;
try{
httpClient = new SSLClient();
httpGet = new HttpGet(url + (params != null ? ("?" + params) : ""));
HttpResponse response = httpClient.execute(httpGet);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity, "utf-8");
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}

Post请求

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
public static String doPost(String url, Map<String,String> params){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = params.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity, "utf-8");
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}

获取Cookie

1
cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();