HttpClientUtil-网络请求工具类

20 篇文章 0 订阅
9 篇文章 0 订阅

import com.google.gson.Gson;
import com.shuidihuzhu.razor.client.utils.json.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuechao
 */
@Slf4j
public class HttpClientUtil {

    @Resource
    private RestTemplate restTemplate;


    /**
     * http get 请求
     *
     * @param url
     * @return
     */
    public static String sendGet(String url) throws Exception {
        log.info("HttpClientUtil sendGet , url = {}", url);

        String responseBody = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000)
                //设置请求和传输超时时间
                .setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);
        //发送请求1
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = httpclient.execute(httpGet, responseHandler);

        //请求方式2
        return responseBody;
    }

    /**
     * http post 请求
     *
     * @param url
     * @param map     key value  参数名称  参数值
     * @param charset
     * @return
     */
    public static String sendPost(String url, Map<String, String> map, String charset) throws Exception {
        Gson gson = GsonUtils.getGson();
        log.info("HttpClientUtil sendPost , url = {} , map = {}, charset = {}", url, gson.toJson(map), charset);

        String responseBody = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000)
                //设置请求和传输超时时间
                .setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        if (null != map) {
            //解析参数
            List<NameValuePair> nameValues = new ArrayList<>();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                NameValuePair nvp = new BasicNameValuePair(entry.getKey(), entry.getValue());
                nameValues.add(nvp);
            }
            //post请求
            //设置参数和编码
            if (StringUtils.isNotEmpty(charset)) {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValues, charset));
            } else {
                httpPost.setEntity(new UrlEncodedFormEntity(nameValues, "UTF-8"));
            }
            //发送请求1
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = httpClient.execute(httpPost, responseHandler);

        }
        log.info("HttpClientUtil sendPost , responseBody= {}", responseBody);
        return responseBody;
    }


    /**
     * 工具类使用示例
     * xxxx
     * @return xxxx,为空则失败
     */
    private Object xxxx1(){
        Gson gson = GsonUtils.getGson();

        //构建初始化授权
        Map<String, String> map = new HashMap<String,String>();
        //	正整数,取值3-10位数字
        map.put("cno", "123");


        //https://api-{region}.xxx.cn/xxx/{xxx}/xxx/xxx
        /**
         *
         *      * 1.线上
         *      * 2.测试
         */
        String agentUrl = "https://api-";
        String defaultTestStatus = "1";
        if(defaultTestStatus.equals("123")){
            agentUrl = agentUrl;
        }else {
            agentUrl = agentUrl + "test-";
        }
        agentUrl = agentUrl + "xxx" + ".xxx.cn/xxx/" + "xxx" + "/xxx/xxx";
        try {
            String responseBody = HttpClientUtil.sendPost(agentUrl, map, null);
            if(StringUtils.isBlank(responseBody)){
                throw new RuntimeException("xxxx sendPost result is empty");
            }
            return responseBody;
        } catch (Exception e) {
            log.error("xxxx has exception, agentUrl = {}, map = {}", agentUrl, gson.toJson(map),e);
            return null;
        }
    }


    /**
     * headerContentType不同
     * xxx2
     * @param phoneNum 号
     * @return xxx2,
     */
    private Object xxx2(String url,String phoneNum){
        Gson gson = GsonUtils.getGson();

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        String infoStr = "{\"filter\": {\"phone\": \"" + phoneNum + "\"}}";
        map.add("info", infoStr);
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        header.set("Authorization", "accessToken");
        try {
            HttpEntity<MultiValueMap<String,Object>> httpEntity = new HttpEntity<>(map, header);

            String responseBody = restTemplate.postForObject(url, httpEntity, String.class);
            if(StringUtils.isBlank(responseBody)){
                throw new RuntimeException("XXX2 postForObject result is empty");
            }

            return responseBody;
        } catch (Exception e) {
            log.error("XXX2 has exception, ",e);
            return null;
        }
    }


    /**
     * headerContentType不同
     * xxx3
     * @return xxx3,为空则失败
     */
    private Object xxx3(String url){
        Gson gson = GsonUtils.getGson();

        Map<String, Object> map = new HashMap<String, Object>(20);

        List<String> queues = new ArrayList<>(1);
        //技能组Ids
        map.put("queues", queues);
        Map<String, Object> userCallerMap = new HashMap<>(20);
        userCallerMap.put("phones",new ArrayList<>(1));
        userCallerMap.put("groups",new ArrayList<>(1));
        userCallerMap.put("xtels",new ArrayList<>(1));
        map.put("userCaller", userCallerMap);


        Map<String, Object> userDisplayMap = new HashMap<>(20);
        userDisplayMap.put("phones",new ArrayList<>(1));
        userDisplayMap.put("groups",new ArrayList<>(1));
        map.put("userDisplay", userDisplayMap);



        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON_UTF8);

        header.set("Authorization", "accessToken");

        try {
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, header);

            String responseBody = restTemplate.postForObject(url, httpEntity, String.class);
            if(StringUtils.isBlank(responseBody)){
                throw new RuntimeException(
                        "xxx3 postForObject result is empty");
            }
            log.info("xxx3 postForObject result, responseBody = {}", gson.toJson(responseBody));
            return responseBody;
        } catch (Exception e) {
            log.error("xxx3 has exception",e);
            return null;
        }
    }





}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值