【HttpClientUtil 自定义工具类】(避免RestTemplateConfig影响返回接口中文乱码)


HttpClientUtil 自定义工具类

提示:这里描述项目中遇到的问题:

调用接口

package cn.speiyou.qa.odin.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class HttpClientUtil {

    /**
     * 调用post接口--json   JSON.toJSONString(textMessageEntity)
     * @param url
     * @param header
     * @param body
     * @return
     */
    public static JSONObject doPost(String url, Map<String,Object> header, Object body) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String data = JSON.toJSONString(body);
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(data, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        if(!header.isEmpty()){
            //遍历header
            for (String key : header.keySet()) {
                httpPost.setHeader(key, header.get(key).toString());
            }
        }
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        // 响应模型
        CloseableHttpResponse response = null;
        String res = "";
        try{
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);
        }catch (IOException ignored){
        }
        return JSON.parseObject(res);
    }

    /**
     * 调用post接口--x-www-form
     * @param url
     * @param header
     * @return
     */
    public static JSONObject doPostXForm(String url, Map<String,Object> header,Object params) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建httpPost远程连接实例
        String data = JSON.toJSONString(params);
        HttpPost httpPost = new HttpPost(url);
        // 设置请求头
        if(!header.isEmpty()){
            //遍历header
            for (String key : header.keySet()) {
                httpPost.setHeader(key, header.get(key).toString());
            }
        }
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        Map paramMap = (Map)JSON.parse(data);
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历,获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        // 响应模型
        CloseableHttpResponse response = null;
        String res = "";
        try{
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);
        }catch (IOException e){
        }
        return JSON.parseObject(res);
    }

    /**
     * 调用post接口--multipart/form-data
     * @param url
     * @param header
     * @param data
     * @return
     */
    public static JSONObject doPostForm(String url,Map<String,Object> header,String data) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(data, "UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        if(!header.isEmpty()){
            //遍历header
            for (String key : header.keySet()) {
                httpPost.setHeader(key, header.get(key).toString());
            }
        }
        httpPost.setHeader("Content-Type", "multipart/form-data");
        // 响应模型
        CloseableHttpResponse response = null;
        String res = "";
        try{
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);
        }catch (IOException e){
        }
        return JSON.parseObject(res);
    }

    /**
     * 调用get接口
     * @param url
     * @param header
     * @return
     * @throws IOException
     */
    public static JSONObject doGet(String url, Map<String,Object> header){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        if(!header.isEmpty()){
            //遍历header
            for (String key : header.keySet()) {
                httpGet.setHeader(key, header.get(key).toString());
            }
        }
        CloseableHttpResponse response = null;
        String res = "";
        try{
            response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);

        }catch (IOException e){
        }
        return JSON.parseObject(res);
    }

    /**
     * 调用get接口-特殊
     * @param url
     * @param header
     * @return
     * @throws IOException
     */
    public static String doGetString(String url, Map<String,Object> header) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        if(!header.isEmpty()){
            //遍历header
            for (String key : header.keySet()) {
                httpGet.setHeader(key, header.get(key).toString());
            }
        }
        CloseableHttpResponse response = null;
        String res = "";
        try{
            response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);
        }catch (IOException e){
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kimberly_zxy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值