一个httpcomponents-client-4.3 httpclient的例子
Apache的httpclient项目一直在升级,从httpclient3.1 项目到httpcomponents-client 4.0再到4.3都不是太稳定,现在处于4.3版本,终于基本稳定下来。现在httpclient3.1已经中止,官方强烈推荐升级到httpcomponents-client 。
其实开发一个功能完整强大的httpclient客户端还是不容易的。这里只是贴出一个使用httpcomponents-client里CloseableHttpClient进行http请求的例子,但是就这几行代码已经内置对Cookie和SSL的处理。谈不上很安全,但至少对使用Cookie对Https的URL是可以处理取回内容的。
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpComponentTest {
public CloseableHttpClient createHttpsClient() {
X509TrustManager x509mgr = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sslContext.init(null, new TrustManager[] { x509mgr }, null);
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// CloseableHttpClient httpclient = HttpClients.createDefault();
HttpComponentTest t=new HttpComponentTest();
CloseableHttpClient httpclient = t.createHttpsClient();
// HttpGet httpGet = new HttpGet("http://www.google.com.hk/search?hl=zh&ie=utf-8&num=30&output=rss&q=java+%7C+hibernate+%7C+spring&tbm=blg");
HttpGet httpGet = new HttpGet("https://www.google.com.hk/search?hl=zh&ie=utf-8&num=30&output=rss&q=java+%7C+hibernate+%7C+spring&tbm=blg");
// HttpGet httpGet = new HttpGet("http://itindex.net/");
try {
HttpResponse httpResp = httpclient.execute(httpGet);
int statusCode = httpResp.getStatusLine().getStatusCode();
if (statusCode == 200) {
System.out.println(EntityUtils.toString(httpResp.getEntity()));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpGet.releaseConnection();
}
}
}