JAVA利用HttpClient进行HTTPS接口调用

JAVA利用HttpClient进行HTTPS接口调用

为了避免需要证书,用一个类继承DefaultHttpClient类,忽略校验过程。

package com.elink.util;
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;
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;

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));
    }
}
package com.elink.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpsClient {
    public static String doPost(String jsonstr, String charset, Map map){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(StringUtils.getStringByObj(map.get("url")));

            if(StringUtils.isNotEmptyObject(map.get("C-DynAmic-Password-Foruser"))){
                httpPost.addHeader("C-DynAmic-Password-Foruser", StringUtils.getStringByObj(map.get("C-DynAmic-Password-Foruser")));
            }
            if(StringUtils.isNotEmptyObject(map.get("C-Business-Id"))){
                httpPost.addHeader("C-Business-Id", StringUtils.getStringByObj(map.get("C-Business-Id")));
            }
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("C-App-Id", StringUtils.getStringByObj(map.get("C-App-Id")));
            httpPost.addHeader("Referer", StringUtils.getStringByObj(map.get("Referer")));
            httpPost.addHeader("C-Tenancy-Id", StringUtils.getStringByObj(map.get("C-Tenancy-Id")));

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

    public static String doGet(Map<String, Object> paramMap) {
        HttpClient httpClient = null;
        HttpResponse response = null;
        String result = "";
        try {
            // 创建httpGet远程连接实例
            httpClient = new SSLClient();
            HttpGet httpGet = new HttpGet(StringUtils.getStringByObj(map.get("url")));
            // 设置请求头信息,鉴权
            httpGet.setHeader("C-App-Id", StringUtils.getStringByObj(paramMap.get("C-App-Id")));
            httpGet.setHeader("C-Business-Id", StringUtils.getStringByObj(paramMap.get("C-Business-Id")));
            httpGet.setHeader("C-Dynamic-Password", StringUtils.getStringByObj(paramMap.get("C-Dynamic-Password")));
            httpGet.setHeader("C-Tenancy-Id", StringUtils.getStringByObj(paramMap.get("C-Tenancy-Id")));
            httpGet.setHeader("Referer", StringUtils.getStringByObj(paramMap.get("Referer")));
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 请求超时时间
                    .setSocketTimeout(60000)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            try {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
public Map test(HttpServletRequest request, @RequestParam Map param) {
	Map resultMap = new HashMap();
	String url = "https://zwfwxtzx.shaanxi.gov.cn:8000/hcp/hcp11000";
	String appMark = "shichangjianduguanlijusx";
	String appPwd = "YN4pbqSDFESDsdfsf";//生产
	String publicKeysm2 = "043592da575f6707d7491cbc971613hb01f4c85a46146deb47368d665390daedd8cdf177d0697ea8e28fa32c2de8cd1";
	String time = TimeUtils.getNowFormatTimeStringyyyyMMddHHmmssSSS();
	String businessId = time + StringUtils.getStringByObj(Double.valueOf(Math.random() * 10000000).intValue());

	//获取验证sign
	JSONObject signObj = new JSONObject();
	signObj.put("time", time);
	signObj.put("appMark", appMark);
	signObj.put("appPwd", appPwd);
	signObj.put("publicKeysm2", publicKeysm2);
	String sign = this.toGetSignParam(signObj);

	//获取加密业务参数
	param.put("publicKeysm2",publicKeysm2);
	param.put("realName",request.getSession().getAttribute("realName"));
	param.put("IDNumberDocumentType",request.getSession().getAttribute("IDNumberDocumentType"));
	param.put("IDNumber",request.getSession().getAttribute("IDNumber"));
	String evaluate = this.toGetSecretParam(param);

	JSONArray jsonArray = new JSONArray();
	jsonArray.add(evaluate);
	JSONObject evaluateObj = new JSONObject();
	evaluateObj.put("evaluate", jsonArray);

	//组装请求参数
	JSONObject pushdata = new JSONObject();
	pushdata.put("appMark", appMark);
	pushdata.put("time", time);
	pushdata.put("sign", sign);
	pushdata.put("params", evaluateObj);

	JSONObject data = new JSONObject();
	data.put("txnBodyCom", pushdata);
	data.put("txnCommom", new HashMap<>());

	try {
		Map paramMap = new HashMap();
		paramMap.put("C-App-Id","2009674556app67202017120111730");
		paramMap.put("C-Tenancy-Id","61560000000000");
		paramMap.put("Referer","https://zwfwxtzx.shaanxi.gov.cn:8000");
		paramMap.put("url",url);
		String result = HttpsClient.doPost(data.toJSONString(),"UTF-8",paramMap);
		System.out.println("推送办件数据="+result);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return resultMap;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值