使用HTTPClient发送请求

1.get

package com.me.modules.httpclient.get;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
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.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *  get请求 带参数;
 */
public class DemoHTTPGet02 {
    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient=null;
        HttpGet httpGet=null;
        HttpEntity responseEntity=null;
        CloseableHttpResponse response=null;
        try {
            //1.创建httpclient对象、
            httpClient = HttpClients.createDefault();
            //请求类型-get  --参数是请求地址;
//             httpGet = new HttpGet("https://www.bilibili.com/");

            /**
             * get请求传参; http://127.0.0.1:8080/weavernorth9/demojsp/a.jsp
             */
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("Userid","47"));
            //协议、域名、端口、参数;
            URI url = new URIBuilder().setScheme("http").setHost("127.0.0.1:8080/weavernorth9/demojsp/a.jsp").setPort(8080).setParameters(params).build();
            httpGet = new HttpGet(url);





            //2.发请求(    1.get/post类型,       2。地址);
            response = httpClient.execute(httpGet);
            //3.判断响应是否正常
            if (response.getStatusLine().getStatusCode() == 200) {
                //获取相应数据;
                responseEntity = response.getEntity();
                System.out.println("响应数据-->"+responseEntity);//此处打印的是对象--地址;
                //将相应数据以html形式显示;
                String HtmlResult = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println("响应数据html形式-->"+HtmlResult);// {”code“:200}---这里可以返回了;
                System.out.println(JSON.parseObject(HtmlResult).getString("code")); //200
            }else{
                System.out.println("请求地址是"+httpGet.getURI()+"响应状态码是"+response.getStatusLine().getStatusCode());
            }
        }catch (Exception e) {
            //打印异常栈信息;
            e.printStackTrace();
        }finally {
            //正常情况下 都是try catch异常信息;
            if (response!=null){
                response.close();
            }
            if (httpClient!=null){
                httpClient.close();
            }


        }


    }
}

2.post

package com.me.modules.httpclient.post;

import com.alibaba.fastjson.JSON;
import com.me.modules.excel.easyexcel.Student;
import org.apache.http.HttpEntity;
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.util.EntityUtils;

import java.io.IOException;


/**
 *
 使用httpclient发送 Post请求,带参数;
 */
public class DemoHTTPPost02 {
    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient=null;
        HttpPost httpPost=null;
        HttpEntity responseEntity=null;
        CloseableHttpResponse response=null;
        try {
            //1.创建httpclient对象、
            httpClient = HttpClients.createDefault();
            //请求类型-post  --参数是请求地址;
            httpPost = new HttpPost("https://www.bilibili.com/");

            /**
             * 1.设置请求参数;
             */
//            List<BasicNameValuePair> params = new ArrayList<>();
//            BasicNameValuePair parm1 = new BasicNameValuePair("id","1");
//            BasicNameValuePair parm2 = new BasicNameValuePair("name","小楚");
//            BasicNameValuePair parm3 = new BasicNameValuePair("age","23");
//            params.add(parm1);
//            params.add(parm2);
//            params.add(parm3);
//            UrlEncodedFormEntity httpEntity = new UrlEncodedFormEntity(params,"UTF-8");//参数1键值对集合,参数2编码;
//            //设置请求的参数
//            httpPost.setEntity(httpEntity);//参数类型是httpEntity,(具体实现类UrlEncodedFormEntity);

            /**
             * 2.设置请求参数--json类型
             */
            //创建对象;
            Student student = new Student();
            student.setName("xiaochu");
            //对象转json
            String jsonString = JSON.toJSONString(student);
            //{a:1,b:2}
            StringEntity httpEntity =new StringEntity(jsonString,"UTF-8");
            httpPost.setEntity(httpEntity);

            //设置头
          //  httpPost.setHeader("Content-type","text/html;charset=utf-8");

            //2.发请求(    1.get/post类型,       2。地址);
            response = httpClient.execute(httpPost);
            //3.判断响应是否正常
            if (response.getStatusLine().getStatusCode() == 200) {
                //获取相应数据;
                responseEntity = response.getEntity();
                System.out.println("响应数据-->"+responseEntity);//此处打印的是对象--地址;
                //将相应数据以html形式显示;
                String HtmlResult = EntityUtils.toString(responseEntity, "UTF-8");
                System.out.println("响应数据html形式-->"+HtmlResult);// {”code“:200}---这里可以返回了;
                System.out.println(JSON.parseObject(HtmlResult).getString("code")); //200
            }else{
                System.out.println("请求地址是"+httpPost.getURI()+"响应状态码是"+response.getStatusLine().getStatusCode());
            }
        }catch (Exception e) {
            //打印异常栈信息;
            e.printStackTrace();
        }finally {
            //正常情况下 都是try catch异常信息;
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }


    }
}

3.常用工具类

package com.util.clj.httputil;

import com.alibaba.nacos.client.config.utils.IOUtils;
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.config.RequestConfig;
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.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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description Http|Https 请求工具类
 * @Author
 * @Date 2022/7/8
 * @Version 1.0
 */
public class HttpUtils {

    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 7000;

    static {

        // 设置连接池
        connMgr = new PoolingHttpClientConnectionManager();

        // 设置连接池大小
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

        RequestConfig.Builder configBuilder = RequestConfig.custom();

        // 设置连接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);

        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_TIMEOUT);

        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);

        // 在提交请求之前 测试连接是否可用
        connMgr.setValidateAfterInactivity(5000);
        // configBuilder.setStaleConnectionCheckEnabled(true);

        requestConfig = configBuilder.build();
    }

    /**
     * 发送 GET 请求(HTTP),不带参数
     *
     * @param url
     * @return
     */
    public  String doGet(String url) {
        return doGet(url, new HashMap<>());
    }

    /**
     * 发送 GET 请求(HTTP),传入参数为 Key-Value 形式
     *
     * @param url
     * @param params
     * @return
     */
    public  String doGet(String url, Map<String, Object> params) {
        String apiUrl = url;
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0)
                param.append("?");
            else
                param.append("&");
            param.append(key).append("=").append(params.get(key));
            i++;
        }
        apiUrl += param;
        String result = null;
        HttpClient httpclient = HttpClientBuilder.create().build();
        try {
            HttpGet httpPost = new HttpGet(apiUrl);
            //设置请求头传入 coolie 用于本地测试 添加cokie  // httpPost.setHeader("","");

            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();

            System.out.println("执行状态码 : " + statusCode);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inStream = entity.getContent();
                result = IOUtils.toString(inStream, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送 POST 请求(HTTP),不带参数
     *
     * @param apiUrl
     * @return
     */
    public  String doPost(String apiUrl) {
        return doPost(apiUrl, new HashMap<>());
    }

    /**
     * 发送 POST 请求(HTTP),参数为 Key-Value 形式
     *
     * content-Type  www-from........
     * @param apiUrl API接口URL
     * @param params 参数map
     * @return
     */
    public  String doPost(String apiUrl, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            httpPost.setConfig(requestConfig);
            List<NameValuePair> pairList = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
                        .getValue().toString());
                pairList.add(pair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, String.valueOf(Charset.forName("UTF-8"))));
            response = httpClient.execute(httpPost);
            System.out.println(response.toString());
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }

    /**
     * 发送 POST 请求(HTTP),参数为JSON形式
     *
     *
     * @param apiUrl
     * @param json   json对象  入参jsonobject类型
     * @return
     */
    public  String doPost(String apiUrl, Object json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine().getStatusCode());
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一路向楠i

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

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

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

打赏作者

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

抵扣说明:

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

余额充值