iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Springboot使用RestTemplate调用第三方接口的操作代码
  • 619
分享到

Springboot使用RestTemplate调用第三方接口的操作代码

RestTemplate调用第三方接口SpringBoot使用RestTemplate 2022-12-08 20:12:35 619人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录前言Spring Boot如何使用RestTemplate总结前言 工作当中,经常会使用到很多第三方提供的功能或者我们自己家也会提供一些功能给别人使用。一般都是通过相互调用api

前言

工作当中,经常会使用到很多第三方提供的功能或者我们自己家也会提供一些功能给别人使用。
一般都是通过相互调用api接口的形式,来进行业务功能的对接。
这里所讲的API接口,一般是指Http(s)形式的请求,遵循RESTful的标准。
传统情况下,在Java代码里面访问restful服务,一般使用Apache的HttpClient,不过此种方法使用起来非常繁琐。
spring从3.0开始提供了一种非常简单的模板类来进行操作,这就是RestTemplate。

Spring Boot如何使用RestTemplate

1、在项目pom.xml文件中引入WEB,依赖内容如下:

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

一般项目中都会已有此依赖。

2、封装RestTemplate配置类RestTemplateConfig(一般放在api/conf目录),代码如下:

package com.***.api.conf;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.ReGIStry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.Socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(httpRequestFactory());
    }

    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(3000);
        connectionManager.setDefaultMaxPerRoute(1000);

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(3000)
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .build();

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}

3、使用举例
举例调用第三方的一个API接口(POST),根据手机号码获取用户的个人信息。

	@Override
    public UserInfo isUserHasCalendar(RestTemplate restTemplate, String sMobile) {
        JSONObject postData = new jsONObject();
        postData.put("mobile", sMobile);
        // URL为第三方HTTP接口地址
        String URL = “******”;
        return restTemplate.postForEntity(URL, postData, UserInfo.class).getBody();
    }

再拿对接过的小鹅通API接口,举例。
小鹅通开放API接口文档:
文档地址: https://api-doc.xiaoe-tech.com/
1)调用“获取access_token”接口:
此接口的官方文档:

在这里插入图片描述

请求方式为get,关键代码如下:

 public String getXiaoETongToken(RestTemplate restTemplate) {
        String url = "https://api.xiaoe-tech.com/token?app_id=app******&client_id=xop******&secret_key=******&grant_type=client_******";
        ResponseEntity<JSONObject> results = restTemplate.exchange(url, HttpMethod.GET, null, JSONObject.class);
        Token tokenDto = JSONObject.toJavaObject(results.getBody(), Token.class);
        return tokenDto.getData().getAccess_token();
    }

2)调用“查询单个用户信息”接口
此接口的官方文档:

在这里插入图片描述

请求方式为post,通过user_id获取用户信息的关键代码如下:

public XiaoETongUser getXiaoETongUser(RestTemplate restTemplate, String Token, String userId) {
        XiaoETongUser user = null;
        try {
            String url = "https://api.xiaoe-tech.com/xe.user.info.get/1.0.0";
            JSONObject postData = new JSONObject();
            postData.put("access_token", Token);
            postData.put("user_id", userId);
            Map map = new HashMap();
            String[] list = {"name", "nickname", "wx_uNIOn_id", "wx_open_id", "wx_app_open_id", "wx_avatar"};
            map.put("field_list", list);
            postData.put("data", map);
            ResultMap resultMap = restTemplate.postForEntity(url, postData, ResultMap.class).getBody();
            if (resultMap.get("code").equals(0)) {
                String data = JSON.toJSONString(resultMap.get("data"));
                user = JSONObject.parseObject(data, XiaoETongUser.class);
            }
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return user;
    }

总结

上面,我只演示了最常使用的请求方式get、post的简单使用方法,当然RestTemplate的功能还有很多,比如:请求方式为delete、put等等,我就不一一举例了,感兴趣的可以去看看RestTemplate的源码

到此这篇关于SpringBoot使用RestTemplate调用第三方接口的文章就介绍到这了,更多相关RestTemplate调用第三方接口内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Springboot使用RestTemplate调用第三方接口的操作代码

本文链接: https://www.lsjlt.com/news/174288.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作