HttpClient调用第三方接口

总结了一个HttpClient调用第三方接口的方法
首先引入相关包

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

其次,代码逻辑如下

	/**
	 * I/O操作
	 * @param method
	 * @return
	 * @throws Exception
	 */
	public static byte[] readResponseStream(HttpMethodBase method) throws Exception{
		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
		InputStream is = method.getResponseBodyAsStream();
		byte[] buffer = new byte[4096];
		while (true) {
			int size = is.read(buffer);
			if (size <= 0) {
				break;
			}
			arrayOutputStream.write(buffer, 0, size);
		}
		return arrayOutputStream.toByteArray();
	}
	/**
	 * http调用方法
	 * @param serviceUrl 调用地址
	 * @param inMsg 参数(JSON)
	 * @return
	 * @throws Exception
	 */
	public static String httpPost(String serviceUrl,String inMsg) throws Exception{
		HttpClientParams clientParam=new HttpClientParams();
		clientParam.setConnectionManagerTimeout(500000);
		clientParam.setSoTimeout(500000);
		clientParam.setConnectionManagerClass(MultiThreadedHttpConnectionManager.class);
		clientParam.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
		HttpClient client=new HttpClient();
		client.setParams(clientParam);
		PostMethod method=new PostMethod(serviceUrl);
		method.releaseConnection();
		method.addRequestHeader("Content-Type","application/json;charset=UTF-8");
		method.setRequestBody(inMsg);
		client.executeMethod(method);
		byte[] responseBytes=readResponseStream(method);
		if(responseBytes!=null){
			return new String(responseBytes);
		}
		return null;
	}

若接口是https协议,则采用下面逻辑:

public String sendHttpsPostUrl(String url, String json, int timeout, Header... headers) throws Exception {
        String result = null;
        CloseableHttpClient httpClient = null;
        HttpPost request;
        try {
            request = new HttpPost(new URI(url));
            StringEntity s = new StringEntity(json, "utf-8");
            s.setContentType("application/json; charset=UTF-8");
            request.setEntity(s);
            for (Header header : headers) {
                request.addHeader(header);
            }
            //设置超时时间
            //setConnectTimeout:设置连接超时时间,单位毫秒
            //setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒
            //setSocketTimeout:请求获取数据的超时时间,单位毫秒
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout)
                    .setSocketTimeout(timeout).build();
            if (needProxy) {
                // 依次是代理地址,代理端口号,协议类型
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                request.setConfig(requestConfig.custom().setProxy(proxy).build());
            }
            request.setConfig(requestConfig);
            //采用绕过验证的方式处理https请求
            SSLContext sslcontext = createIgnoreVerifySSL();
            // 设置协议http和https对应的处理socket链接工厂的对象
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext))
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClientBuilder builder= HttpClientBuilder.create().setConnectionManager(connManager);
            httpClient=builder.build();
            HttpContext localContext = new BasicHttpContext();
            HttpResponse response = httpClient.execute(request,localContext);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, "utf-8");
            }
        } catch (Exception e) {
            log.error("发送sendHttpsPostUrl请求异常", e);
            throw new Exception(e);
        }
        return result;
    }
public static String sendHttpsGetUrl(String url, Header... headers) throws Exception {
        int timeout = 10000;//10秒超时
        // 响应内容
        String szRlt = null;
        // 创建默认的httpClient实例
        CloseableHttpClient httpClient = null;
        try {
            try {
                //采用绕过验证的方式处理https请求
                SSLContext sslcontext = createIgnoreVerifySSL();
                // 设置协议http和https对应的处理socket链接工厂的对象
                Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                        .register("https", new SSLConnectionSocketFactory(sslcontext))
                        .build();
                PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

                HttpClientBuilder builder= HttpClientBuilder.create().setConnectionManager(connManager);
                httpClient=builder.build();
            } catch (Exception e){
                log.info("绕过验证的方式处理https请求",e);
                throw new Exception(e);
            }
            // 创建HttpGet
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout)
                    .setSocketTimeout(timeout).build();
            if (needProxy) {
                // 依次是代理地址,代理端口号,协议类型
                HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                httpGet.setConfig(requestConfig.custom().setProxy(proxy).build());
            }
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("content-type", "application/json");
            for (Header header : headers) {
                httpGet.addHeader(header);
            }
            // 执行GET请求
            HttpContext localContext = new BasicHttpContext();
            HttpResponse response = httpClient.execute(httpGet,localContext);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                szRlt = EntityUtils.toString(entity, "utf-8");
            }
            log.info("Https Get请求返回的结果是"+szRlt);
        } catch (Exception e1) {
            log.info("绕过验证的方式处理https请求",e1);
            throw new Exception(e1);
        }
        return szRlt;
    }

具体应用案例可参考:RSA生成公私钥并加解密

欢迎大家积极留言交流学习心得,点赞的人最美丽,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值