httpClient发送get和post请求的工具类

引入的maven依赖:

 <dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5.4</version>
 </dependency>
 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.74</version>
 </dependency>
 <dependency>
     <groupId>commons-lang</groupId>
     <artifactId>commons-lang</artifactId>
     <version>2.6</version>
 </dependency>

工具类:

public class RequestUtil {

    /**
     * 发送get请求-无参
     * @param url 请求url
     * @param headers 请求头
     * @return 响应体
     */
    public static String sendGetRequestNoParams(String url, Map<String, String> headers){
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        if(headers != null){
            headers.forEach(httpGet::setHeader);
        }

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 发送get请求
     * @param url 请求url
     * @param paramsMap 参数
     * @param headers 请求头
     * @return 响应体
     */
    public static String sendGetRequestNeedParams(String url, Map<String, String> paramsMap, Map<String, String> headers){
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 参数拼接
        List<String> params = new ArrayList<>();
        paramsMap.forEach((key,value)->{
            try {
                // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
                params.add(key + "=" + URLEncoder.encode(value, "utf-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        });
        String paramsStr = String.join("&", params);
        if(StringUtils.isNotEmpty(paramsStr)){
            url += "?" + paramsStr;
        }
        System.out.println("url=" + url);

        // 创建Get请求
        HttpGet httpGet = new HttpGet(url);
        // 设置请求头
        if(headers != null){
            headers.forEach(httpGet::setHeader);
        }

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();
            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
               return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 发送post请求
     * @param url 请求url
     * @param requestDataJson 请求体的数据,json格式
     * @param headers 请求头
     * @return 响应体
     */
    public static String sendPostRequestByJson(String url, String requestDataJson, Map<String, String> headers) {
        // 设置代理,使用Fiddler抓包工具
        // HttpHost proxy = new HttpHost("localhost", 8888, "http");
        // RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        // CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        // ----------------------------------------------------------------------------------------------------

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 将json数据放入entity中
        StringEntity entity = new StringEntity(requestDataJson, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        if(headers != null){
            headers.forEach(httpPost::setHeader);
        }
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 发送post请求,表单形式,请求体放对象,而不是json串
     * @param url 请求url
     * @param params 请求体中的参数
     * @param headers 请求头
     * @return
     */
    public static String sendPostRequestByForm(String url, Map<String, String> params, Map<String, String> headers) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        // 将请求数据放置请求体中
        List<BasicNameValuePair> paramList = new ArrayList<>();
        params.forEach((key,value)->{
            paramList.add(new BasicNameValuePair(key, value));
        });
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(formEntity);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        if(headers != null){
            headers.forEach(httpPost::setHeader);
        }
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
HttpClientJava中的一个开源库,用于支持HTTP协议的客户端编程。它是一个用于发送HTTP请求和接收HTTP响应的包装工具类HttpClient可以被用于执行GET和POST请求HTTP方法。走看看是一个基于Web的应用程序,包含了各种常见的网站功能,如搜索、资讯、体育、财经、购物等多个频道。下面将分别介绍HttpClient发送GET和POST请求时的一些重要知识点。 HttpClient发送GET请求时,需要构造一个HttpGet对象,并指定请求的URL。调用HttpClient.execute方法,并且将HttpGet对象传递给该方法。接下来,HttpClient发送GET请求到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 HttpClient发送POST请求时,需要首先构造一个HttpPost对象,并指定请求的URL。调用HttpPost.setEntity方法来设置请求体内容,然后调用HttpClient.execute方法,并将HttpPost对象传递给该方法。接下来,HttpClient会将POST请求数据发送到指定的URL,然后将响应内容作为一个HttpResponse对象返回给程序。与GET请求相似,可以从HttpResponse对象中获取响应状态、响应头和响应体等信息。 总的来说,HttpClient是一个十分强大和方便的网络编程工具类,可以方便地实现HTTP请求和响应的处理。可以根据自己的需求选择GET和POST请求发送,然后获取响应内容和各种信息。使用HttpClient能够简化开发,提高编程效率,是Java网络编程开发中非常重要的一种库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值