HttpClient请求接口实例demo
HttpClient是Apache中的一个开源的项目。它实现了HTTP标准中Client端的所有功能,使用它能够很容易地进行HTTP信息的传输。HttpClient的主要功能:
- 实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
- 支持 HTTPS 协议
- 支持代理服务器(Nginx)
- 支持自动(跳转)转向 等等
HttpCLient最关键的方法是执行HTTP请求的方法execute。只要把HTTP请求传入,就可以得到HTTP响应。
使用HttpClient请求一个Http请求的步骤为:
(1)创建一个HttpClient对象
(2)创建一个Request对象
(3)使用HttpClient来执行Request请求,得到对方的response
(4)处理response
(5)关闭HttpClient
本人使用的是fegin包下面的httpclient ,当然也可以使用 httpcomponents下的依赖。
接下来我们在idea中进行尝试一下。首先引入httpClient的maven依赖。
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
</dependency>
httpcomponents pom 目前最高的可以点击下方的链接去查看
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
代码如下
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
//POST 请求
HttpPost httpPost = new HttpPost();
//GET 请求
HttpGet httpGet = new HttpGet("");
//设置接口请求头信息
httpPost.addHeader("Authorization","xxx");
httpPost.addHeader("Content-Type", "application/json;charset=utf8");
CloseableHttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
//TODO 在这里处理请求后的数据逻辑
System.out.println(result);
}
//5.关闭资源
response.close();
httpClient.close();
}
}
具体的httpGet类中的代码如下
package org.apache.http.client.methods;
import java.net.URI;
public class HttpGet extends HttpRequestBase {
public static final String METHOD_NAME = "GET";
public HttpGet() {
}
public HttpGet(URI uri) {
this.setURI(uri);
}
public HttpGet(String uri) {
this.setURI(URI.create(uri));
}
public String getMethod() {
return "GET";
}
}
分类:
程序员与bug
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结