HttpClientUtil 工具类

使用Apache HttpClient进行HTTP请求的方法示例
  /**
     *  * CloseableHttpClient类 ,client实现类
     *  * HttpClients类 ,client工具类,用于创建客户端对象。
     *  * CloseableHttpResponse接口,请求的响应对象
     *  * URIBuilder类 :url构建类,用于设置get请求的路径变量
     *  * HttpGet类 :get请求的发送对象
     *  * EntityUtils类 实体处理类
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url,Map<String, String> params){

        //获取httpclient客户端
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";

        CloseableHttpResponse response = null;

        try {
            URIBuilder builder = new URIBuilder(url);

            if(null!=params){
                for (String key:params.keySet()) {
                    builder.setParameter(key, params.get(key));
                }
            }

            HttpGet get = new HttpGet(builder.build());


            response = httpclient.execute(get);

            System.out.println(response.getStatusLine());

            if(200==response.getStatusLine().getStatusCode()){
                HttpEntity entity = response.getEntity();
                resultString = EntityUtils.toString(entity, "utf-8");
            }

        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            if(null!=response){
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(null!=httpclient){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return resultString;
    }


    /**
     *    CloseableHttpClient类
     *  * HttpClientBuilder client构建对象,用于创建客户端对象。
     *  * LaxRedirectStrategy类,post请求重定向的策略
     *  * CloseableHttpResponse 请求的响应对象
     *  * HttpPost post请求的发送对象
     *  * NameValuePair 类,用于设置参数值
     *  * UrlEncodedFormEntity:用于设置表单参数给发送对象HttpPost
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url,Map<String,String> params){
        /**
         * 在4.0及以上httpclient版本中,post需要指定重定向的策略,如果不指定则按默认的重定向策略。
         *
         * 获取httpclient客户端
         */
        CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy( new LaxRedirectStrategy()).build();

        String resultString = "";

        CloseableHttpResponse response = null;

        try {


            HttpPost post = new HttpPost(url);

            List<NameValuePair> paramaters = new ArrayList<>();

            if(null!=params){
                for (String key : params.keySet()) {
                    paramaters.add(new BasicNameValuePair(key,params.get(key)));
                }

                UrlEncodedFormEntity  formEntity = new UrlEncodedFormEntity (paramaters);

                post.setEntity(formEntity);
            }


            /**
             * HTTP/1.1 403 Forbidden
             *   原因:
             *      有些网站,设置了反爬虫机制
             *   解决的办法:
             *      设置请求头,伪装浏览器
             */
            post.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");

            response = httpclient.execute(post);

            System.out.println(response.getStatusLine());

            if(200==response.getStatusLine().getStatusCode()){
                HttpEntity entity = response.getEntity();
                resultString = EntityUtils.toString(entity, "utf-8");
            }

        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            if(null!=response){
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(null!=httpclient){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return resultString;
    }

package com.li.modul.joinDemo.util;


import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @author 阿杰
 * @effect post请求
 * @date 2022/4/8
 * @versions 1.0
 */
public class HttpClientUtils{
    /**
     * 模拟表单执行post请求
     * @param url 请求地址
     * @param headers 请求头信息
     * @param params 请求参数
     * @return  java.lang.String
     * @author A
     * @date 2020/5/20 17:41
     **/
    public static  String doPostByForm(String url, Map<String,String> headers, Map<String,Object> params) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 表单方式
            // 创建参数列表
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                entity.setContentEncoding("UTF-8");
                httpPost.setEntity(entity);
            }
            // 添加httpHeaders
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    httpPost.addHeader(key, headers.get(key));
                }
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            // 获取响应消息
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     *  json类型参数 post请求
     * @param url
     * @param headers 请求头信息
     * @param json
     * @return  java.lang.String
     * @author A
     * @date 2020/5/20 17:52
     **/
    public static String doPostByJson(String url,Map<String,String> headers, String json) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try{
            //创建httpPost请求
            HttpPost httpPost = new HttpPost(url);
            //给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            // 添加httpHeaders
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    httpPost.addHeader(key, headers.get(key));
                }
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            // 获取响应消息
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return resultString;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟小杰子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值