http请求方式-HttpClient 微信退款的接口,需要证书请求 https请求

http请求方式-HttpClient

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.core.mydemo.http.OrderReqVO;
import org.apache.http.HttpEntity;
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.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Map;

public class HttpClientUtils {

    /**
     * 参考微信退款的接口,需要证书请求。
     * @param url
     * @param params
     * @param useCert
     * @return
     * @throws Exception
     */
    public static String executeJson(String url, String params, boolean useCert) throws Exception {
        BasicHttpClientConnectionManager connManager;
        if(useCert) {
            char[] password = "123456".toCharArray();
            String certFilePath = "F:/wxpay/my_app_cert.p12";
            System.out.println("certFilePath=" + certFilePath);

            InputStream certStream = new FileInputStream(new File(certFilePath));
            //InputStream certStream = H5PayHttpComponent.class.getResourceAsStream(WxPayConstants.WX_PAY_H5_CERT_P12);

            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(certStream, password);

            // 实例化密钥库 & 初始化密钥工厂
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, password);

            // 创建 SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    new DefaultHostnameVerifier());

            connManager = new BasicHttpClientConnectionManager(
                    RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
                            .register("https", sslConnectionSocketFactory)
                            .build(),
                    null,
                    null,
                    null
            );
        } else {
            connManager = new BasicHttpClientConnectionManager(
                    RegistryBuilder.<ConnectionSocketFactory>create()
                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
                            .register("https", SSLConnectionSocketFactory.getSocketFactory())
                            .build(),
                    null,
                    null,
                    null
            );
        }
        HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(6000).build();
        httpPost.setConfig(requestConfig);

//        StringEntity postEntity = new StringEntity(params, "UTF-8");
//        httpPost.addHeader("Content-Type", "text/xml");
//        httpPost.addHeader("User-Agent", "WXPaySDK/3.0.9"+" (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
//                ") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion() + " "+wxPayAppConfig.getMchid());
//        httpPost.setEntity(postEntity);

        StringEntity entity = new StringEntity(params,"utf-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity, "UTF-8");
    }

    public static void main(String[] args) {

        OrderReqVO data = new OrderReqVO();
        data.setOrderNum("111123333");
        data.setServerType("1");

        String url = "https://域名/接口名称";

        try {
            System.out.println("返回结果=" + executeJson(url,JSON.toJSONString(data),false));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 

posted on 2022-10-13 19:10  oktokeep  阅读(87)  评论(0编辑  收藏  举报