HttpUtils http请求工具类

2021-06-28 12:06

阅读:611

标签:stack   post   cat   map   eof   释放   apache   ati   list   


import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class HttpClientUtils {
    /**
     * get请求
     */
    public static String doGet(String hostPath, Map headers, Map querys) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(buildUrl(hostPath, querys));
        httpGet.setHeader("Content-Type", "multipart/form-data");
        for (Map.Entry e : headers.entrySet()) {
            httpGet.addHeader(e.getKey(), e.getValue());
        }
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            return responseEntityProcessStr(response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }
    /**
     * post请求
     */
    public static String doPost(String hostPath, Map headers, Map querys, Map bodys) throws Exception{
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(buildUrl(hostPath, querys));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        // 响应模型
        CloseableHttpResponse response = null;
        for (Map.Entry e : headers.entrySet()) {
            httpPost.addHeader(e.getKey(), e.getValue());
        }
        try {
            if (bodys != null) {
                List nameValuePairList = new ArrayList();
                for (String key : bodys.keySet()) {
                    nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "utf-8"));
            }
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            return responseEntityProcessStr(response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    private static String buildUrl(String hostPath, Map querys) throws UnsupportedEncodingException {
        if (null != querys) {
            StringBuilder sbUrl = new StringBuilder(hostPath);
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry query : querys.entrySet()) {
                sbQuery.append("&");
                if (StringUtils.isBlank(query.getKey()) && query.getValue()!=null) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (query.getValue()!=null) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(String.valueOf(query.getValue()), "utf-8"));
                    }
                }
            }
            if (0  List responseEntityProcess(CloseableHttpResponse response, Class r) throws Exception {
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();

        System.out.println("响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            String s = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            System.out.println("响应内容为:" + s);
            return Collections.singletonList(JSON.parseObject(s, r));
        }
        return null;
    }

    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            String group = matcher.group(2);
            ch = (char) Integer.parseInt(group, 16);
            String group1 = matcher.group(1);
            str = str.replace(group1, ch + "");
        }
        return str;
    }

}

HttpUtils http请求工具类

标签:stack   post   cat   map   eof   释放   apache   ati   list   

原文地址:https://www.cnblogs.com/fly-book/p/14930149.html

上一篇:解决PHP大数据量

下一篇:.Net Core + Autofac


评论


亲,登录后才可以留言!