欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > 苍穹外卖学习笔记(十一)

苍穹外卖学习笔记(十一)

2024/10/25 5:19:58 来源:https://blog.csdn.net/qq_73340809/article/details/142500649  浏览:    关键词:苍穹外卖学习笔记(十一)

一. HttpClient

介绍

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

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.14</version>
</dependency>

该项目导入了阿里的sdk,传递依赖
核心API:

  1. HttpClient
  2. HttpClients
  3. CloseableHttpClient
  4. HttpGet
  5. HttpPost

发生请求步骤:

  1. 创建HttpClient对象
  2. 创建Http请求对象
  3. 调用HttpClient的execute方法发送请求

入门案例

HttpClientTest.java

package com.sky.test;import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class HttpClientTest {/*** 测试HttpClient发送get请求*/@Testpublic void testGet() {// 创建HttpClient对象CloseableHttpClient aDefault = HttpClients.createDefault();// 创建HttpGet对象HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");// 发送请求try {CloseableHttpResponse execute = aDefault.execute(httpGet);// 获取响应数据int statusCode = execute.getStatusLine().getStatusCode();System.out.println("状态码:" + statusCode);HttpEntity entity = execute.getEntity();String string = EntityUtils.toString(entity);System.out.println("响应数据:" + string);// 关闭资源execute.close();aDefault.close();} catch (Exception e) {e.printStackTrace();}}/*** 测试HttpClient发送post请求*/@Testpublic void testPost() throws Exception {// 创建HttpClient对象CloseableHttpClient aDefault = HttpClients.createDefault();// 创建HttpPost对象HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");JSONObject jsonObject = new JSONObject();jsonObject.put("username", "admin");jsonObject.put("password", "123456");StringEntity entity = new StringEntity(jsonObject.toString());// 设置请求头entity.setContentEncoding("UTF-8");// 设置请求体entity.setContentType("application/json");httpPost.setEntity(entity);// 发送请求CloseableHttpResponse execute = aDefault.execute(httpPost);// 获取响应数据int statusCode = execute.getStatusLine().getStatusCode();System.out.println("状态码:" + statusCode);HttpEntity entity1 = execute.getEntity();String string = EntityUtils.toString(entity1);System.out.println("响应数据:" + string);// 关闭资源execute.close();aDefault.close();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com