码迷,mamicode.com
首页 > Web开发 > 详细

HttpUtils http请求工具类

时间:2021-06-25 17:08:46      阅读:0      评论:0      收藏:0      [点我收藏+]

标签: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<String, String> headers, Map<String, Object> querys) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(buildUrl(hostPath, querys));
        httpGet.setHeader("Content-Type", "multipart/form-data");
        for (Map.Entry<String, String> 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<String, String> headers, Map<String, Object> querys, Map<String, String> 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<String, String> e : headers.entrySet()) {
            httpPost.addHeader(e.getKey(), e.getValue());
        }
        try {
            if (bodys != null) {
                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
                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<String, Object> querys) throws UnsupportedEncodingException {
        if (null != querys) {
            StringBuilder sbUrl = new StringBuilder(hostPath);
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, Object> 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 < sbQuery.length()) {
                return sbUrl.append("?").toString() + sbQuery.append("&").toString().substring(1);
            }
        }
        return hostPath;
    }

    private static String responseEntityProcessStr(CloseableHttpResponse response) 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);
            s = unicodeToString(s);
            System.out.println("响应内容为:" + s);
            return s;
        }
        return null;
    }

    private static <R> List<R> responseEntityProcess(CloseableHttpResponse response, Class<R> 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!