使用httpclient的SSL握手响应403

时间:2016-10-12 12:05:40

标签: java web-services ssl soap httpclient

我是Https协议的新手,希望使用apache httpclient来使用基于SOAP的Web服务。

当我从Soap UI客户端调用Web服务时,它工作正常,但当我从httpclient调用相同的.net文件时,它正在响应403禁止。

以下是我的httpclient代码

import java.io.ByteArrayOutputStream;

import javax.net.ssl.SSLContext;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import java.math.BigInteger;

import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.KeyManagementException;

import java.security.PublicKey;
import java.security.cert.X509Certificate;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;


public class HttpClientFactory {

    private static CloseableHttpClient client;

    public HttpClient getHttpsClient() throws Exception {

        if (client != null) {
            return client;
        }
        SSLContext sslcontext = getSSLContext();


        SSLConnectionSocketFactory factory =
            new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy(){

            @Override
            public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
                // TODO Implement this method
                return 15000;
            }
        };

        client = HttpClients.custom().setSSLSocketFactory(factory).setKeepAliveStrategy(myStrategy).setHostnameVerifier(new AllowAllHostnameVerifier()).build();

        return client;
    }

    public static void releaseInstance() {
        client = null;
    }

    private SSLContext getSSLContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
                                              IOException, KeyManagementException {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream =
            new FileInputStream(new File("Test.jks"));

        try {
            trustStore.load(instream, "password".toCharArray());
        } finally {
            instream.close();
        }
        final TrustStrategy trustStrategy = new TrustStrategy() {
            public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
                for (X509Certificate cer : chain)
                    printCertificate(cer);
                return true;
            }
        };
        return SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
    }


    public static void main(String[] args) {

        System.setProperty("javax.net.debug", "ssl:handshake");

        CloseableHttpClient httpclient = null;
        try {
            httpclient = (CloseableHttpClient) new HttpClientFactory().getHttpsClient();

        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpPost httpPost = new HttpPost("<POST URL>");
        httpPost.setHeader("Accept-Encoding", "gzip,deflate");
        httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
        httpPost.setHeader("SOAPAction", "");
        httpPost.setHeader("Connection", "Keep-Alive");

        String payload = Constants.REQUEST;
            HttpEntity entity = new StringEntity(payload,HTTP.UTF_8);
            httpPost.setEntity(entity);

        HttpResponse response = null;
        try {
            System.out.println("Program started");
            response = httpclient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();

            ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            inputStream.close();
            System.out.println(result.toString("UTF-8"));

        } catch (ClientProtocolException e) {
            System.out.println("ClientProtocol");
        } catch (IOException e) {
            System.out.println("IOException");
        } finally { 
        }
    }
}

请帮我摆脱这个问题。

0 个答案:

没有答案