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";
    }
}

posted @   烫手的山芋  阅读(647)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示