使用HttpClient 4.5的Httget请求

时间:2015-08-12 14:19:10

标签: java ssl httpclient

我试图更新使用HttpClient 4.5的代码没有弃用的方法,但是找到解决方案是完全不可能的,我完全迷失了。

这是我的代码:

public int sendGetHTTP() throws QAException, IOException {
    HttpResponse httpResponse = null;
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        InputStream is = new FileInputStream("my");

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate caCert = (X509Certificate)cf.generateCertificate(is);

        TrustManagerFactory tmf = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        ks.setCertificateEntry("cert", caCert);

        tmf.init(ks);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme scheme = new Scheme("https", sf, 444);
        client.getConnectionManager().getSchemeRegistry().register(scheme);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpGet httpGet = new HttpGet("https://mysite:444/en.html");
        httpGet.addHeader("SSO-EMPLOYEENUMBER", "1234");
        httpResponse = client.execute(httpGet);
    } catch (Exception e) {
        e.printStackTrace();
    }
    int status = httpResponse.getStatusLine().getStatusCode();
    if (status != HTTP_STATUS_OK && status != HTTP_STATUS_CREATED) {
        throw new QAException("Server Response: " + status + ": " + httpResponse.getStatusLine().getReasonPhrase());
    }
    return status;
}

如何将此代码更改为不使用已弃用的方法和实例(如DefaultHttpClient)?

我能阅读哪些有用的文件吗?

1 个答案:

答案 0 :(得分:0)

Apache维护deprecated list

您可以查看该列表,了解他们建议您更换的内容,以及不推荐使用的客户端版本。

对于DefaultHttpClient,他们建议

  

org.apache.http.impl.client.DefaultHttpClient(4.3)使用   HttpClientBuilder还可以看到CloseableHttpClient。

您还可以转到HttpComponents Home Page,其中包含指向示例和文档

的链接