周梦康 发表于 2016-01-25 3616 次浏览 标签 : JavaHttpClient

httpClient 没有配置 SSL 会出现如下错误

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.conn.ssl.SSLSocketFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by zhoumengkang on 25/1/16.
 */
public class sendPost {

    public static HttpClient getClient(boolean isSSL) {

        HttpClient httpClient = new DefaultHttpClient();

        if (isSSL) {
            X509TrustManager xtm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };

            try {
                SSLContext ctx = SSLContext.getInstance("TLS");

                ctx.init(null, new TrustManager[]{xtm}, null);

                SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

                httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        return httpClient;
    }

    public static String postData(String url, String data, Header[] headers) {
        HttpClient   httpClient   = getClient(true);
        String       responseText = "";
        HttpResponse httpResponse = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().
                    setSocketTimeout(5000).
                    setConnectTimeout(5000).
                    build();
            httpPost.setConfig(requestConfig);

            httpPost.setHeaders(headers);

            httpPost.setEntity(new StringEntity(data, "UTF-8"));

            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                responseText = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseText;
    }
}

发送测试

BasicHeader[] basicHeaders = new BasicHeader[1];
basicHeaders[0] = new BasicHeader("Content-Type","application/json");

String res = sendPost.postData(tokenApi, jsonObject.toString(),basicHeaders);

里面有很多方法都是废弃的,不建议使用,后面再改吧。

参考 https://github.com/easemob/emchat-server-examples/blob/master/emchat-server-java/src/main/java/com/easemob/server/example/httpclient/utils/HTTPClientUtils.java

评论列表