Http请求工具类

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();
    }

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中有多种HTTP请求工具类可供使用,其中一种是http-request。它基于URLConnection实现,不依赖于HttpClient。使用http-request发送GET请求示例如下: 1. 引入依赖: ``` <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>5.6</version> </dependency> ``` 2. 发送GET请求获取响应报文: ```java String response = HttpRequest.get("http://www.baidu.com").body(); System.out.println("Response was: " + response); ``` 3. 发送GET请求获取响应码: ```java int code = HttpRequest.get("http://google.com").code(); ``` 除了http-request,还有其他一些常用的HTTP请求工具类,比如HttpUtil。使用HttpUtil发送GET请求的示例代码如下: ```java // 最简单的HTTP请求,自动判断编码 String result1 = HttpUtil.get("https://www.baidu.com"); // 自定义请求页面的编码 String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8); // 传入http参数,参数会自动做URL编码,拼接在URL中 HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result3 = HttpUtil.get("https://www.baidu.com", paramMap); ``` 如果需要发送POST请求,可以使用HttpUtil的post方法,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 另外,如果需要文件上传,可以将参数中的键指定为"file",值设为文件对象即可,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>();paramMap.put("file", FileUtil.file("D:\\face.jpg")); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 以上是一些常用的Java HTTP请求工具类,你可以根据具体需求选择适合的工具类来发送HTTP请求。请问您还有其他相关问题吗? 相关问题: 1. Java中还有哪些常用的HTTP请求工具类? 2. 如何处理HTTP请求的返回结果? 3. 如何设置HTTP请求的超时时间?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值