HttpClient

前言

超文本传输协议 (HTTP) 可能是 今天的互联网。Web 服务、支持网络的设备和网络计算的发展 继续将 HTTP 协议的作用扩展到用户驱动的 Web 浏览器之外,同时 增加需要 HTTP 支持的应用程序数量。

尽管 java.net 包提供了通过 HTTP 访问资源的基本功能, 它不能提供许多应用程序所需的全部灵活性或功能。 HttpClient 试图通过提供高效、最新且功能丰富的功能来填补这一空白 实现最新 HTTP 标准和建议的客户端的包。

专为扩展而设计,同时为基本 HTTP 协议 HttpClient 提供强大的支持 任何构建 HTTP 感知客户端应用程序(如 Web 浏览器、Web 服务客户端,或利用或扩展分布式 HTTP 协议的系统 通信。

HttpClient教程

  1. Httpclient作用域
    • 基于 HttpCore 的客户端 HTTP 传输库
    • 基于经典(阻塞)I/O
    • 与内容无关
  2. HttpClient 不是什么
    • HttpClient 不是浏览器。它是一个客户端 HTTP 传输库。 HttpClient 的目的是发送和接收 HTTP 消息。HttpClient 不会 尝试处理内容,执行嵌入在HTML页面中的javascript,尝试猜测 内容类型(如果未显式设置)或重新设置请求/重写位置 URI, 或与 HTTP 传输无关的其他功能。

介绍

HttpClient是Apache Jakarta Common 下的子项目,可以用来提供搞笑的,最新的,功能丰富的支持Http协议的 客户端编程工具包 ,并且它支持HTTP协议最新的版本和建议

使用
导入工具包 或 导入依赖

<dependcy>
	<groupId>org.apach.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>##</version>
</dependcy>

核心API

  • HttpClient----接口
  • Httpclients----工具类
  • CloseanleHttpclient — HttpCient实现类
  • HttpGet
  • HttpPost
  • 。。。。

发送请求步骤

  • 创建HttpClient对象
  • 创建Http请求对象
  • 调用HttpClient的execute方法执行请求
  • 关闭资源

Httpget

	public void testGET(){
        //获取httpclient对象 CloseableHttpClient, 是HttpClient的实现类
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建httpclient的get请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");

        try {
            //执行请求, 返回响应数据
            CloseableHttpResponse response = httpClient.execute(httpGet);

            //获取响应数据
            //状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            //响应实体
            HttpEntity entity = response.getEntity();
            //解析响应实体
            String string = EntityUtils.toString(entity);
            System.out.println(string);

            //关闭响应数据
            response.close();
            //关闭httpclient
            httpClient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

HttpPost

    public void testPOST() throws IOException {
        //获取httpclient对象 CloseableHttpClient, 是HttpClient的实现类
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpclient的post请求对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");

        //设置请求参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "admin");
        jsonObject.put("password", "123456");
            //StringEntity 是 HttpEntity 的实现类
        StringEntity entity = new StringEntity(jsonObject.toJSONString(), "utf-8");
        entity.setContentType("application/json");

        httpPost.setEntity(entity);

        //执行请求, 返回响应数据
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //获取响应数据
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("响应状态码:" + statusCode);

        HttpEntity entity1 = response.getEntity();
        String string = EntityUtils.toString(entity1, "utf-8");
        System.out.println("响应数据:" + string);

        //关闭响应数据
        response.close();
        httpClient.close();
    }

将请求封装为工具类

get请求—基于请求参数

	public static String doGet(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try {
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }
  1. 创建HttpClient对象
  2. 使用URIBuilder构造带参请求路径
  3. 创建HttpGet请求对象
  4. 发送请求
  5. 获取响应
  6. 关闭资源

post请求—基于表单

    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

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

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
  1. 创建HttpPost请求
  2. 构建表单数据
    • UrlEncodeFormEntity(List<? extends NameValuePair> parameters)来模拟表单数据
      参数 List 且 类型为NameValuePair及其子类,NameValuePair为接口,故使用唯一实现类BasicNameValuePair
    • 创建 List < NameValuePair >
    • 封装BasicNameValuePair数据,该类中只有name 和 value两个字段,分别对应表单数据的字段和值。使用构造方法 new BasicNameValuePair(String naem , String value)
    • 将BasicNameValuePair数据添加到 List < NameValuePair > 中
  3. HttpPost设置表单数据 setEntity(HttpEntity entity)。及将UrlEncodeFormEntity设置到实体中,UrlEncodeFormEntity是StringEntity的子类,StringEntity是HttpEntity的子类
  4. 执行httpPost请求
  5. 获取响应
  6. 关闭资源

post请求—基于json字符串

	public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

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

            if (paramMap != null) {
                //构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
                //设置请求编码
                entity.setContentEncoding("utf-8");
                //设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }
  1. 创建HttpPost请求
  2. 将请求参数封装为Json数据格式
    • 使用 fastJson 添加数据 呢哇JSONObject().Put(String key,Object value)
    • 转换成json字符串 toString() / toJSONstring();
  3. 将json字符数据封装为StringEntiy实体
  4. HttpPost设置实体 setEntity(HttpEntity emtity) StrigEntity是HttpEntity的子类
  5. 设置数据 类型JSON “application/json”
    HttpPost。setContenType(“application/json”,“utf-8”)
  6. 执行请求
  7. 关闭数据

想了解更多可去文档查看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小胖子S

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

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

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

打赏作者

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

抵扣说明:

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

余额充值