使用HttpClient封装工具类调用第三方接口

BizServerRestUtils.java

package jiangdu.fire.util;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

@Component
public class BizServerRestUtils {

    private static final Logger log = LoggerFactory.getLogger(BizServerRestUtils.class);

    public static <T> T doExecute(String url,Object requestParam,Class<T> clazz) throws Exception {
        String resultText = null;
        try {
            resultText = NetUtils.post(url, getStringEntity(requestParam), NetUtils.getHttpClient(),getHeader());
            //log.debug("return {}", resultText);
        } catch (IOException e) {
            e.printStackTrace();
           // log.error("请求异常"+e.getMessage(),e);
            throw  e;
        }
        return null;
    }

    public static String doExecute2String(String url, Object requestParam) throws Exception {
        String resultText = null;
        try {
            resultText = NetUtils.post(url, getStringEntity(requestParam), NetUtils.getHttpClient(), getHeader());
            log.debug("return {}", resultText);
        } catch (IOException e) {
            e.printStackTrace();
            //log.error("请求异常" + e.getMessage(), e);
            throw e;
        }
        return resultText;
    }

    public static String doExecute2String(String url, Object requestParam, String jssesionId) throws Exception {
        String resultText = null;
        try {
            resultText = NetUtils.post(url, getStringEntity(requestParam), NetUtils.getHttpClient(), getHeader(jssesionId));
            //log.debug("return {}", resultText);
        } catch (IOException e) {
            e.printStackTrace();
            //log.error("请求异常" + e.getMessage(), e);
            throw e;
        }
        return resultText;
    }

    public static <T> List<T> doExecuteArray(String url, Object requestParam, Class<T> clazz) throws Exception {
        String resultText = null;
        try {
            resultText = NetUtils.post(url, getStringEntity(requestParam), NetUtils.getHttpClient(),getHeader());
            //log.debug("return {}", resultText);
        } catch (IOException e) {
            e.printStackTrace();
           // log.error("请求异常"+e.getMessage(),e);
            throw  e;
        }
        return null;
    }

    private static StringEntity getStringEntity(Object requestParam){
        String jsonParams = JSONObject.toJSONString(requestParam);
        StringEntity stringEntity = new StringEntity(jsonParams, Charset.forName("UTF-8"));
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");//发送json数据需要设置contentType
        return stringEntity;
    }
    private static Map<String,String> getHeader(){
        // 获取随机数和签名
        String result = "";
        String sign = "";
        String nonceStr = "";
        SortedMap<String,String> treeMap = new TreeMap<String, String>();
        treeMap.put("appId","dj1001");
        nonceStr = StringUtils.remove(UUID.randomUUID().toString(), "-");
        treeMap.put("nonceStr",nonceStr);//随机数
        try {
            sign = SignUtils.encodeSign(treeMap,"55DEF8A9F4374B319EF8A9F437AB313E");//key为密钥
        } catch (Exception e) {
            e.printStackTrace();
        }
        SortedMap<String,String> maps = new TreeMap<String, String>();
        maps.put("appId","dj1001");
        maps.put("nonceStr",nonceStr);
        maps.put("sign",sign);
        /*log.info("requestMaps:"+maps);
        log.info("sign:"+sign);*/
        Map<String,String> header = new HashMap<String, String>();
        header.put("appId","dj1001");
        header.put("nonceStr",nonceStr);
        header.put("sign",sign);
        return header;
    }

    private static Map<String, String> getHeader(String jssesionId) {
        // 获取随机数和签名
        String result = "";
        String sign = "";
        String nonceStr = "";
        SortedMap<String,String> treeMap = new TreeMap<String, String>();
        treeMap.put("appId","dj1001");
        nonceStr = StringUtils.remove(UUID.randomUUID().toString(), "-");
        treeMap.put("nonceStr",nonceStr);//随机数
        try {
            sign = SignUtils.encodeSign(treeMap,"55DEF8A9F4374B319EF8A9F437AB313E");//key为密钥
        } catch (Exception e) {
            e.printStackTrace();
        }
        SortedMap<String, String> maps = new TreeMap<String, String>();
        maps.put("appId", "dj1001");
        maps.put("nonceStr", nonceStr);
        maps.put("sign", sign);
        /*log.info("requestMaps:" + maps);
        log.info("sign:" + sign);*/
        Map<String, String> header = new HashMap<String, String>();
        header.put("appId", "dj1001");
        header.put("nonceStr", nonceStr);
        header.put("sign", sign);
        header.put("jssesionId", jssesionId);
        return header;
    }

}

NetUtils.java

package jiangdu.fire.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.Security;
import java.util.Map;

public class NetUtils {
    private static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 200;
    private static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 300;
    private static final CloseableHttpClient client;
    private static String charsetEncoding = "utf-8";

    public NetUtils() {

    }

    public static void setCharsetEncoding(String charsetEncoding) {
        charsetEncoding = charsetEncoding;
    }

    public static HttpClient getHttpClient() {
        return client;
    }

    public static String get(String url) throws URISyntaxException, IOException {
        CloseableHttpResponse response = client.execute(new HttpGet(url));
        return EntityUtils.toString(response.getEntity(), charsetEncoding);
    }

    public static String post(String url, HttpEntity httpEntity, HttpClient httpClient, Map<String,String> header) throws IOException {
        if(httpClient == null) {
            httpClient = client;
        }

        HttpPost post = new HttpPost(url);
        if(header!=null && header.size() >0){
            for(String key : header.keySet()){
                post.addHeader(key,header.get(key));
            }
        }

        post.setEntity(httpEntity);
        return EntityUtils.toString(((HttpClient)httpClient).execute(post).getEntity(), charsetEncoding);
    }

    public static String post(String url, HttpEntity httpEntity) throws IOException {
        return post(url, (HttpEntity)httpEntity, (HttpClient)null,null);
    }

    public static String post(String url, String data, String contentType, HttpClient httpClient) throws IOException {
        return post(url, (byte[])data.getBytes(charsetEncoding), contentType, httpClient);
    }

    public static String post(String url, byte[] data, String contentType, HttpClient httpClient) throws IOException {
        ByteArrayEntity se = new ByteArrayEntity(data);
        se.setContentEncoding(new BasicHeader("Content-Encoding", charsetEncoding));
        se.setContentType(new BasicHeader("Content-Type", contentType));
        return post(url, (HttpEntity)se, (HttpClient)httpClient,null);
    }

    public static String post(String url, String data, String contentType) throws IOException {
        return post(url, (byte[])data.getBytes(charsetEncoding), (String)contentType);
    }

    public static String post(String url, byte[] data, String contentType) throws IOException {
        return post(url, (byte[])data, contentType, (HttpClient)null);
    }

    static {
        System.setProperty("jsse.enableSNIExtension", "false");
        Security.setProperty("networkaddress.cache.ttl", "0");
        RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectionRequestTimeout(30000).setConnectTimeout(5000).build();
        client = HttpClientBuilder.create().setDefaultRequestConfig(config).setMaxConnTotal(200).setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setMaxConnPerRoute(300).disableAutomaticRetries().build();
    }


}

使用工具类的话需要添加依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.1.23</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值