HttpClient 4发送请求

雪域幽狐 2015-10-31 13:55 阅读:6171


HttpClient 4与3比起来,接口变化比较大,特别是https请求部分,直接上代码。
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

/**
 * Title: 测试HttpClient

 * Description: 

 * Copyright: Copyright (c) 2015

 * Company: NowFox Studio

 * @author nowfox
 * @version 1.0 
 * @date 2015-10-31
 */
public class TestHttpClient {

    private static final Log log = LogFactory.getLog(TestHttpClient.class);

    /**
    * 
    * @param url 计划要请求的地址,需要根据这个判断生成HTTPS的连接还是HTTP的连接
    * @return
    */
    public HttpClient getHttpClient(String url) {
        HttpClient httpClient = null;
        if (url.toLowerCase().startsWith("https")) {
            try {
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() {
                            //信任所有
                            public boolean isTrusted(X509Certificate[] chain,
                                    String authType) throws CertificateException {
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext, new NoopHostnameVerifier());
                return HttpClients.custom().setSSLSocketFactory(sslsf).build();
            } catch (Exception e) {
                log.error("创建SSL连接失败", e);
            }
        } else {
            httpClient = HttpClients.createDefault();
        }
        return httpClient;
    }

    public void sendHttpRequest() {
        String url = "http://www.nowfox.com/";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = (CloseableHttpClient) getHttpClient(url);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity);
            log.info(responseStr);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                log.info("关闭流出错", e);
            }
        }
    }

    public static void main(String[] args) {
        TestHttpClient test = new TestHttpClient();
        test.sendHttpRequest();
    }
}

0条评论

登陆后可评论