美文网首页spring boot
HttpClient 调用第三方接口

HttpClient 调用第三方接口

作者: 任未然 | 来源:发表于2019-11-03 22:37 被阅读0次

一、概述

  • HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包。
  • HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。

二、使用示例

2.1 数据提供方

2.1.1 Entity

public class User {
    private int age;
    private String name;
    public User() {
    }
    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

2.1.2 Controller

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping
    public Object getAll(int age) {
        return Arrays.asList(new User(age, "张三"), new User(age, "李四"));
    }
}

2.1.3 访问http://localhost:8080/user

2.2 数据调用方

2.2.1 导包

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--httpclient-->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>
    <!--fastjson-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.60</version>
    </dependency>

2.2.2 Entity

public class User {
    private int age;
    private String name;
    public User() {}
    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

2.2.3 Utils

public class HttpProtocolHandler {
    // 请求方式
    public enum Request_method {
        POST, GET
    }
    // Http连接管理器,该管理器必须是线程安全的
    private static PoolingHttpClientConnectionManager connectionManager;
    // 最大的连接数量
    private int maxTotal = 100;
    // 每个路径最大的连接数
    private int maxConnPerRoute = 20;
    private static HttpProtocolHandler httpProtocolHandler = new HttpProtocolHandler();
    public HttpProtocolHandler() {
        // Http连接池
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(maxConnPerRoute);
    }
    // 提供实例
    public static HttpProtocolHandler getInstance() {
        return httpProtocolHandler;
    }
    // 具体的调用方法
    public String execute(Request_method requestMethod, String url, Map<String, String> paramsMap) {
        String responseStr = null;
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
        List<NameValuePair> nameValuePair = generatNameValuePair(paramsMap);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePair, Consts.UTF_8);
        HttpUriRequest uriRequest = Request_method.GET.equals(requestMethod) ? new HttpGet(generatRequestUrl(url, paramsMap)) : new HttpPost(url);
        if (Request_method.POST.equals(requestMethod)) {
            ((HttpPost) uriRequest).setEntity(entity);
        }
        try {
            HttpResponse httpResponse = httpClient.execute(uriRequest);
            responseStr = EntityUtils.toString(httpResponse.getEntity());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return responseStr;
    }
    // POST请求参数的方法组装
    public static List<NameValuePair> generatNameValuePair(Map<String, String> paramsMap) {
        List<NameValuePair> nameValuePair = new LinkedList<NameValuePair>();
        for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
            nameValuePair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return nameValuePair;
    }
    // GET请求的参数的方法封装
    public static String generatRequestUrl(String url, Map<String, String> paramsMap) {
        StringBuffer fullUrl = new StringBuffer(url);
        if (paramsMap != null && paramsMap.size() > 0) {
            fullUrl.append("?");
            int i = 0;
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                i++;
                String paramName = entry.getKey();
                String paramValue = entry.getValue();
                fullUrl.append(i == paramsMap.size() ? paramName + "=" + paramValue : paramName + "=" + paramValue + "&");
            }
        }
        return fullUrl.toString();
    }
}

使用方法:
HttpProtocolHandler.getInstance().execute(HttpProtocolHandler.Request_method.GET, URL, new HashMap<String, String>())

  • HttpProtocolHandler.Request_method.GET : 请求的类型
  • URL : 请求的URL地址
  • new HashMap<String, String>() : 请求的参数

2.2.4 Controller

@RestController
@RequestMapping("/remote")
public class RemoteController {
    @RequestMapping
    public Object getUser() {
        Map<String, String> map = new HashMap<>();
        map.put("age","18");
        String remoteUrl = "http://localhost:8080/user";
        String result = HttpProtocolHandler.getInstance().execute(HttpProtocolHandler.Request_method.GET, remoteUrl, map);
        List<User> users = JSON.parseArray(result, User.class);
        return users;
    }
}

2.2.5 YML

server:
  port: 8082

2.2.6 Controller 访问http://localhost:8082/remote

相关文章

网友评论

    本文标题:HttpClient 调用第三方接口

    本文链接:https://www.haomeiwen.com/subject/zyilbctx.html