ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Http请求工具类

2021-05-20 19:05:58  阅读:71  来源: 互联网

标签:Http 请求 url res client new 工具 null String


pom依赖

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

工具类


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class HttpUtils {

    public static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);
    private static final RequestConfig CONFIG = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(50000)
            .build();

    private static List<Integer> httpOkCode=new ArrayList<>(10);

    static{
        httpOkCode.add( HttpStatus.SC_OK );
        httpOkCode.add( HttpStatus.SC_CREATED );
        httpOkCode.add( HttpStatus.SC_ACCEPTED );
        httpOkCode.add( HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION );
        httpOkCode.add( HttpStatus.SC_NO_CONTENT );
        httpOkCode.add( HttpStatus.SC_RESET_CONTENT );
        httpOkCode.add( HttpStatus.SC_PARTIAL_CONTENT );
        httpOkCode.add( HttpStatus.SC_MULTI_STATUS );
    }

    /**
     * 执行一个HTTP GET请求,返回请求响应的HTML
     *
     * @param url 请求的URL地址
     * @return 返回请求响应的HTML
     * @throws IOException
     */
    public static String doGet(String url, Map<String, String> params) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(CONFIG).build();
        if (params != null) {
            url = url + "?" + map2Str(params);
        }
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = client.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            } else {
                LOGGER.info("HTTP接口调用状态码为{},非200、非201,调用接口:{}\n参数:{}\n", httpResponse.getStatusLine().getStatusCode(), url, params);
            }
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return "";
    }

    /**
     * 执行一个HTTP POST请求,返回请求响应的HTML
     *
     * @param url 请求的URL地址
     * @return 返回请求响应的HTML
     * @throws IOException
     */
    public static String doPost(String url, Map<String, Object> params) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        if (params != null) {
            StringEntity entity = new StringEntity(JSON.toJSONString(params), Charset.forName("UTF-8"));
            httpPost.setEntity(entity);
        }
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");

        try {
            HttpResponse httpResponse = client.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                    || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                HttpEntity responseEntityentity = httpResponse.getEntity();
                return EntityUtils.toString(responseEntityentity, "utf-8");
            } else {
                LOGGER.info("HTTP接口调用状态码为{},非200、非201,调用接口:{}\n参数:{}\n", httpResponse.getStatusLine().getStatusCode(), url, params);
            }
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return "";
    }
    public static String doPostForm(String url, Map<String, Object> params) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        if (params != null) {
            List<NameValuePair> paramsNameValuePair = new ArrayList<>(params.size());
            params.forEach((key, value) -> {
                NameValuePair nameValuePair = new BasicNameValuePair(key, String.valueOf(value));
                paramsNameValuePair.add(nameValuePair);
            });
            httpPost.setEntity(new UrlEncodedFormEntity(paramsNameValuePair,"UTF-8"));
        }
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");

        try {
            HttpResponse httpResponse = client.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                    || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                HttpEntity responseEntityentity = httpResponse.getEntity();
                return EntityUtils.toString(responseEntityentity, "utf-8");
            } else {
                LOGGER.info("HTTP接口调用状态码为{},非200、非201,调用接口:{}\n参数:{}\n", httpResponse.getStatusLine().getStatusCode(), url, params);
            }
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return "";
    }

    /**
     * 通过HTTP POST方法发送body内容至指定URL
     *
     * @param url  目标URL
     * @param body 发送的内容
     * @throws TestException
     */
    public static void doPost(String url, String body) throws TestException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(CONFIG).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("content-type", "application/json;charset=UTF-8");
        try {
            HttpEntity entity = new StringEntity(body, Consts.UTF_8);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                LOGGER.error("do post exception,the url is:" + url);
                httpPost.abort();
                throw new TestException("Http post error status code :" + statusCode);
            } else {
                LOGGER.info("HTTP接口调用状态码为{},非200、非201,调用接口:{}\n参数:{}\n", statusCode, url, body);
            }
        } catch (Exception e) {
            LOGGER.error("do post exception,the url is:" + url, e);
            throw new TestException(e.getMessage(), e);
        } finally {
            httpPost.releaseConnection();
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
    }

    /**
     * 通用返回
     *
     * @param url post url
     * @param param post params
     * @return post result
     */
    public static String doPostR(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = param.keySet().stream().map(key -> new BasicNameValuePair(key, param.get(key))).collect(Collectors.toList());
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        } finally {
            try {
                if (response != null){
                    response.close();
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
        }

        return resultString;
    }



    /**
     * 
     * post请求
     * @param url
     * @return
     */
    public static String doGet(String url){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        String result=null;
        try {
            get.setHeader("Content-type", "application/json");
            CloseableHttpResponse res = client.execute(get);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode()) ){

                // 获取返回结果
                if(res.getEntity()!=null){
                    result = EntityUtils.toString(res.getEntity());
                }

            }else{
                throw new TestException("ErrorHttpStatusCode"+res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new TestException(e);
        }finally {
            get.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return result;
    }

    /**
     * 
     * Json Post请求
     * @param url
     * @param jsonBody
     * @return
     */
    public static JSONObject doPostJsonCovert(String url, String jsonBody){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(jsonBody);
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            CloseableHttpResponse res = client.execute(post);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode()) ){
                // 返回json格式
                if(res.getEntity()!=null){
                    String result = EntityUtils.toString(res.getEntity());
                    response = JSONObject.parseObject(result);
                }
            }else {
                throw new TestException("HttpStatusCode"+res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            post.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return response;
    }

    /**
     * 
     * Json Post请求
     * @param url
     * @param jsonBody
     * @return
     */
    public static String doPostJson(String url, String jsonBody){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        String response = null;
        try {
            post.addHeader("Content-Type", "application/json; charset=utf-8");
            StringEntity s = new StringEntity(jsonBody,"utf-8");
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            CloseableHttpResponse res = client.execute(post);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode()) ){
                // 返回json格式
                if(res.getEntity()!=null){
                    response = EntityUtils.toString(res.getEntity());
                }
            }else {
                throw new TestException("HttpStatusCode"+res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            post.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return response;
    }

    /**
     * 
     * Json Post请求
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPostJson(String url, JSONObject json){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            CloseableHttpResponse res = client.execute(post);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode()) ){
                // 返回json格式
                if(res.getEntity()!=null){
                    String result = EntityUtils.toString(res.getEntity());
                    response = JSONObject.parseObject(result);
                }
            }else {
                throw new TestException("HttpStatusCode"+res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            post.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return response;
    }


    /**
     * 
     * post请求 返回array 对象
     * @param url
     * @param json
     * @return
     */
    public static JSONArray doPostJsonArray(String url, JSONObject json){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONArray response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            post.setEntity(s);
            CloseableHttpResponse res = client.execute(post);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode()) ){
                // 返回json格式
                if(res.getEntity()!=null){
                    String result = EntityUtils.toString(res.getEntity());
                    response = JSONObject.parseArray(result);
                }

            }else{
                throw new TestException("ErrorHttpStatusCode"+res.getStatusLine().getStatusCode());

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            post.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return response;
    }

    /**
     * 
     * PUT请求 body 为json格式
     * @param url
     * @return
     */
    public static String doPut(String url,String jsonBody){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpPut put = new HttpPut(url);
        String result=null;
        try {
            if(jsonBody!=null){
                jsonBody=jsonBody.replaceAll("\\\t","").replaceAll("\\\n","");
            }
            put.setHeader("Content-type", "application/json");
            StringEntity s = new StringEntity(jsonBody);
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            put.setEntity(s);
            CloseableHttpResponse res = client.execute(put);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode())){
                // 返回json格式:
                if(res.getEntity()!=null){
                    result = EntityUtils.toString(res.getEntity());
                }

            }else{
                throw new TestException("ErrorHttpStatusCode"+res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new TestException(e);
        }finally {
            put.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return result;
    }

    /**
     * 
     * get请求 返回JOSN
     * @param url
     * @return
     */
    public static JSONObject doGetJson(String url){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        JSONObject response = null;
        try {
            get.setHeader("Content-type", "application/json");
            CloseableHttpResponse res = client.execute(get);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode() )){
                // 返回json格式:
                if(res.getEntity()!=null){
                    String result = EntityUtils.toString(res.getEntity());
                    response = JSONObject.parseObject(result);
                }

            }else{
                throw new TestException("ErrorHttpStatusCode"+res.getStatusLine().getStatusCode());

            }
        } catch (Exception e) {
            throw new TestException(e);
        }finally {
            get.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return response;
    }

    /**
     * 
     * get请求返回array对象
     * @param url
     * @return
     */
    public static JSONArray doGetJsonArray(String url){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        JSONArray response = null;
        try {
            get.setHeader("Content-type", "application/json");
            CloseableHttpResponse res = client.execute(get);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode())){
                // 返回json格式:
                if(res.getEntity()!=null){
                    String result = EntityUtils.toString(res.getEntity());
                    response = JSONObject.parseArray(result);
                }

            }else{
                throw new TestException("ErrorHttpStatusCode"+res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new TestException(e);
        }finally {
            get.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return response;
    }

    /**
     *
     * 
     * delete请求 返回 json对象
     * @param url
     * @return
     */
    public static JSONObject doDeleteJson(String url){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpDelete delete = new HttpDelete(url);
        JSONObject response = null;
        try {
            delete.setHeader("Content-type", "application/json");
            CloseableHttpResponse res = client.execute(delete);
            if(httpCodeIsOk(res.getStatusLine().getStatusCode())){
                // 返回json格式:
                if(res.getEntity()!=null){
                    String result = EntityUtils.toString(res.getEntity());
                    if(result!=null && result.trim().length()>0){
                        response = JSONObject.parseObject(result);
                    }
                }

            }else{
                throw new TestException("ErrorHttpStatusCode"+res.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new TestException(e);
        }finally {
            delete.releaseConnection();
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                LOGGER.error("close client exception", e);
            }
        }
        return response;
    }


    /**
     * 执行一个HTTP DELETE请求,返回请求响应的HTML
     *
     * @param url 请求的URL地址
     * @return 返回请求响应的HTML
     * @throws IOException
     */
    public static String doDelete(String url) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpDelete httpDelete = new HttpDelete(url);
        try {
            HttpResponse response = client.execute(httpDelete);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity, "utf-8");
            } else {
                LOGGER.info("HTTP接口调用状态码为{},非200、非201,调用接口:{}\n", response.getStatusLine().getStatusCode(), url);
            }
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return "";
    }

    /**
     * Map对象转为字符串
     *
     * @param   params map param
     * @return  转换后的参数
     * @throws UnsupportedEncodingException
     */
    private static String map2Str(Map<String, String> params) throws UnsupportedEncodingException {
        if (params == null || params.size() == 0) {
            return "";
        }
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {
                //拼接时,不包括最后一个&字符
                sb.append(key).append("=").append(value);
            } else {
                sb.append(key).append("=").append(value).append("&");
            }
        }
        return sb.toString();
    }

    private static Boolean httpCodeIsOk(int httpCode){
        return httpOkCode.contains(httpCode);
    }

}

自定义异常类

/**
 * The base class of all other exceptions
 * @Author: ZhiWen
 */
public class TestException extends RuntimeException {

    private final static long serialVersionUID = 1L;

    public TestException(String message, Throwable cause) {
        super(message, cause);
    }

    public TestException(String message) {
        super(message);
    }

    public TestException(Throwable cause) {
        super(cause);
    }

    public TestException() {
        super();
    }

}

我打算去微博和知乎讲故事

标签:Http,请求,url,res,client,new,工具,null,String
来源: https://blog.csdn.net/zhiwenshow/article/details/117088227

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有