您的位置:首页 > 理论基础 > 计算机网络

httpclient发送https的get请求忽略证书

2017-11-27 09:54 387 查看
1.首先创建一个HttpsClient类

import java.security.KeyManagementException;

import java.security.NoSuchAlgorithmException;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;

import org.apache.http.conn.ClientConnectionManager;

import org.apache.http.conn.scheme.Scheme;

import org.apache.http.conn.scheme.SchemeRegistry;

import org.apache.http.conn.ssl.SSLSocketFactory;

import org.apache.http.impl.client.DefaultHttpClient;

public class HttpsClient {

private static X509TrustManager tm = new X509TrustManager() {

public void checkClientTrusted(X509Certificate[] xcs, String string)throws CertificateException {

}

public void checkServerTrusted(X509Certificate[] xcs, String string)throws CertificateException {

}

public X509Certificate[] getAcceptedIssuers() {

return null;

}

};

@SuppressWarnings("deprecation")

public static HttpClient getInstance() throws KeyManagementException,NoSuchAlgorithmException {

HttpClient client = new DefaultHttpClient();

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

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

SSLSocketFactory ssf = new SSLSocketFactory(ctx);

ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

ClientConnectionManager ccm = client.getConnectionManager();

SchemeRegistry sr = ccm.getSchemeRegistry();

sr.register(new Scheme("https", ssf, 443));

client = new DefaultHttpClient(ccm, client.getParams());

return client;

}

}

2.然后写一个发送请求(get请求)的方法​

public static JSONObject requestGet(String url) {

//get请求返回结果

JSONObject jsonResult = null;

try {​

//常规的http请求时这样的

//CloseableHttpClient httpClient = HttpClients.createDefault();​

//在这里获取HttpsClient的一个实例作为httpclient的一个对象

HttpClient httpsClient = HttpsClient.getInstance();

//发送get请求

HttpGet request = new HttpGet(url);

HttpResponse response = httpsClient.execute(request);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

String strResult = EntityUtils.toString(response.getEntity());

jsonResult = JSONObject.parseObject(strResult);

url = URLDecoder.decode(url, "UTF-8");

} else {

logger.error("通信异常:" + url);

}

} catch (IOException e) {

logger.error("通信异常:" + url, e);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (KeyManagementException e) {

e.printStackTrace();

}

return jsonResult;

}

3.发送http的post请求

public static JSONObject jsonPost(String url, JSONObject jsonParam, boolean noNeedResponse) {

        //post请求返回结果

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost method = new HttpPost(url);

        try {

            if (null != jsonParam) {

                //解决中文乱码问题

                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");

                entity.setContentEncoding("UTF-8");

                entity.setContentType("application/json");

                method.setEntity(entity);

            }

            HttpResponse result = httpClient.execute(method);

            url = URLDecoder.decode(url, "UTF-8");

           

            return buildResult(url, result, noNeedResponse);

        } catch (IOException e) {

            logger.error("通信异常:" + url, e);

        }

        return null;

    }

   

    public static JSONObject httpPost(String url, Map postMap, boolean noNeedResponse) {

        //post请求返回结果

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost method = new HttpPost(url);

        try {

            if (null != postMap) {

                //解决中文乱码问题

                List params = new ArrayList<>();

                for (String key : postMap.keySet()) {

                    params.add(new BasicNameValuePair(key, postMap.get(key)));

                }

                method.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

            }

            HttpResponse result = httpClient.execute(method);

            url = URLDecoder.decode(url, "UTF-8");

            return buildResult(url, result, noNeedResponse);

        } catch (IOException e) {

            logger.error("通信异常:" + url, e);

        }

        return null;

    }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: