java 远程调用 httpclient 调用https接口 忽略SSL认证

httpclient 调用https接口,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。下面是忽略校验过程的代码类:SSLClient 

package com.pms.common.https;

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.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;

/**
 * 用于进行Https请求的HttpClient
 * @ClassName: SSLClient
 * @Description: TODO
 *
 */
public class SSLClient extends DefaultHttpClient {

    public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, getTrustingManager(), null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }

    private static TrustManager[] getTrustingManager() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        return trustAllCerts;
    }
}

然后再调用的远程get、post请求中使用SSLClient 创建Httpclient ,代码如下:

package com.pms.common.https;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpsClientUtil {

    /**
     * post请求(用于请求json格式的参数)
     * @param url
     * @param param
     * @return
     */
    @SuppressWarnings("resource")
    public static String doHttpsPost(String url, String param, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            StringEntity se = new StringEntity(param);
            se.setContentType("application/json;charset=UTF-8");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * post请求(用于key-value格式的参数)
     * @param url
     * @param params
     * @return
     */
    @SuppressWarnings("resource")
    public static String doHttpsPostKV(String url, Map<String,Object> params, String charset, Map<String, String> headers){
        BufferedReader in = null;
        try {
            // 定义HttpClient
            HttpClient httpClient = new SSLClient();
            // 实例化HTTP方法
            HttpPost httpPost = new HttpPost();

            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }

            httpPost.setURI(new URI(url));

            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));

                //System.out.println(name +"-"+value);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            HttpResponse response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if(code == 200){    //请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(),"utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }

                in.close();

                return sb.toString();
            }
            else{   //
                System.out.println("状态码:" + code);
                return null;
            }
        }
        catch(Exception e){
            e.printStackTrace();

            return null;
        }
    }

    @SuppressWarnings("resource")
    public static String doHttpsGet(String url, Map<String, Object> params, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try{
            if(params !=null && !params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<>(params.size());
                for (String key :params.keySet()){
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                url +="?"+EntityUtils.toString(new UrlEncodedFormEntity(pairs), charset);
            }
            httpClient = new SSLClient();
            httpGet = new HttpGet(url);
//            httpGet.addHeader("Content-Type", "application/json");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpGet.addHeader(next.getKey(), next.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }


    
    //get 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8
    //带参数
    @SuppressWarnings("resource")
    public static String doHttpsFormUrlencodedGetRequest(String url, Map<String, Object> params, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try{
            if(params !=null && !params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<>(params.size());
                for (String key :params.keySet()){
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
                url +="?"+EntityUtils.toString(new UrlEncodedFormEntity(pairs), charset);
            }
            httpClient = new SSLClient();
            httpGet = new HttpGet(url);
            httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//            httpGet.addHeader("Content-Type", "application/json");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpGet.addHeader(next.getKey(), next.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    //post 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8
    //带参数
    @SuppressWarnings("resource")
    public static String doHttpsFormUrlencodedPostRequest(String url, String param, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            StringEntity se = new StringEntity(param);
            se.setContentType("application/x-www-form-urlencoded;charset=utf-8");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    //post 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8
    //不带参数  或者参数拼接在url中
    public static String doHttpsFormUrlencodedPostNoParam(String url, String charset, Map<String, String> headers){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
//            url = url+URLEncoder.encode("{1}", "UTF-8");
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }

    //传文件到远程post接口
    public static String sendPostWithFile(String url, String param,Map<String, String> headers,File file) throws Exception{
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", new FileBody(file));
            HttpEntity multipartEntity = builder.build();
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            httpPost.setEntity(multipartEntity);
            StringEntity se = new StringEntity(param);
//            se.setContentType("multipart/form-data;charset=utf-8");
//            se.setContentEncoding(new BasicHeader("Content-Type", "multipart/form-data;charset=utf-8"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);

            //获取接口返回值
            InputStream is = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            StringBuffer bf = new StringBuffer();
            String line= "";
            while ((line = in.readLine()) != null) {
                bf.append(line);
            }

            System.out.println("发送消息收到的返回:"+bf.toString());
            return bf.toString();
        }catch(Exception ex){
            ex.printStackTrace();
        }
       return result;

    }

    /**
     * @param @param  url
     * @param @param  formParam
     * @param @param  proxy
     * @param @return
     * @return String
     * @throws
     * @Title: httpPost
     * @Description: http post请求
     * UrlEncodedFormEntity Content-Type=application/x-www-form-urlencoded
     */
    public static String httpPostbyFormHasProxy(String url, Map<String,String> param,Map<String, String> headers,File file) throws IOException {

        log.info("请求URL:{}", url);
        long ls = System.currentTimeMillis();
        HttpPost httpPost = null;
        HttpClient httpClient = null;
        String result = "";
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", new FileBody(file));
            HttpEntity multipartEntity = builder.build();
            httpPost = new HttpPost(url);
            if (headers != null) {
                Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, String> next = iterator.next();
                    httpPost.addHeader(next.getKey(), next.getValue());
                }
            }
            List<NameValuePair> paramList = transformMap(param);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, "utf8");
            httpPost.setEntity(formEntity);
            httpClient = new SSLClient();
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int code = httpResponse.getStatusLine().getStatusCode();
            log.info("服务器返回的状态码为:{}", code);

            if (code == HttpStatus.SC_OK) {// 如果请求成功
                    result = EntityUtils.toString(httpResponse.getEntity());

            }

        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally {
            if (null != httpPost) {
                httpPost.releaseConnection();
            }
            long le = System.currentTimeMillis();
            log.info("返回数据为:{}", result);
            log.info("http请求耗时:ms", (le - ls));
        }
        return result;

    }

    /**
     * @param @param  params
     * @param @return
     * @return List<NameValuePair>
     * @throws @Title: transformMap
     * @Description: 转换post请求参数
     */
    private static List<NameValuePair> transformMap(Map<String, String> params) {
        if (params == null || params.size() < 0) {// 如果参数为空则返回null;
            return new ArrayList<NameValuePair>();
        }
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> map : params.entrySet()) {
            paramList.add(new BasicNameValuePair(map.getKey(), map.getValue()));
        }
        return paramList;
    }

}

猜你喜欢

转载自blog.csdn.net/k0307x1990y/article/details/126622419