https接口调用工具类

    最近做的项目,需要调通第三方接口,于是研究了调用https接口的工具类,用来调用post请求的接口。

/*
 * 使用HttpClient进行post请求的工具类
 *
 */
public class HttpClientUtil{


    public static String doPost(String url,String jsonstr,String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            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;
    }
}

/*
 * 用于进行Https请求的HttpClient
 *
 */

public class SSLClient extends DefaultHttpClient {

    public SSLClient() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, 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));
    }
}

使用示例:

//查询入參
JSONObject params = new JSONObject();

 String time="2021-09-16";

params.put("time", time);

//接口url (自定义的)

 String url="https://abs.com:108080/api/"; 

HttpClientUtil.doPost(url, params.toString(), "utf-8");

版权声明:本文为zhou134174原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。