欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot使用RestTemplate調(diào)用第三方接口的操作代碼

 更新時(shí)間:2022年12月05日 10:10:29   作者:技術(shù)經(jīng)理老晶  
這篇文章主要介紹了Springboot使用RestTemplate調(diào)用第三方接口,我只演示了最常使用的請求方式get、post的簡單使用方法,當(dāng)然RestTemplate的功能還有很多,感興趣的朋友可以參考RestTemplate源碼

前言

工作當(dāng)中,經(jīng)常會使用到很多第三方提供的功能或者我們自己家也會提供一些功能給別人使用。
一般都是通過相互調(diào)用API接口的形式,來進(jìn)行業(yè)務(wù)功能的對接。
這里所講的API接口,一般是指HTTP(s)形式的請求,遵循RESTful的標(biāo)準(zhǔn)。
傳統(tǒng)情況下,在Java代碼里面訪問restful服務(wù),一般使用Apache的HttpClient,不過此種方法使用起來非常繁瑣。
Spring從3.0開始提供了一種非常簡單的模板類來進(jìn)行操作,這就是RestTemplate。

Spring Boot如何使用RestTemplate

1、在項(xiàng)目pom.xml文件中引入web,依賴內(nèi)容如下:

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

一般項(xiàng)目中都會已有此依賴。

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、使用舉例
舉例調(diào)用第三方的一個(gè)API接口(POST),根據(jù)手機(jī)號碼獲取用戶的個(gè)人信息。

	@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)調(diào)用“獲取access_token”接口:
此接口的官方文檔:

在這里插入圖片描述

請求方式為get,關(guān)鍵代碼如下:

 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)調(diào)用“查詢單個(gè)用戶信息”接口
此接口的官方文檔:

在這里插入圖片描述

請求方式為post,通過user_id獲取用戶信息的關(guān)鍵代碼如下:

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

總結(jié)

上面,我只演示了最常使用的請求方式get、post的簡單使用方法,當(dāng)然RestTemplate的功能還有很多,比如:請求方式為delete、put等等,我就不一一舉例了,感興趣的可以去看看RestTemplate的源碼。

到此這篇關(guān)于Springboot使用RestTemplate調(diào)用第三方接口的文章就介紹到這了,更多相關(guān)RestTemplate調(diào)用第三方接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解SpringBoot?JPA常用注解的使用方法

    詳解SpringBoot?JPA常用注解的使用方法

    這篇文章主要介紹了SpringBoot?JPA常用注解的使用方法,spring?boot作為當(dāng)前主流的技術(shù),來看看常用的注解怎么用,如果有錯誤的地方還請指正,需要的朋友可以參考下
    2023-03-03
  • Idea設(shè)置全局highlighting?level為Syntax問題

    Idea設(shè)置全局highlighting?level為Syntax問題

    這篇文章主要介紹了Idea設(shè)置全局highlighting?level為Syntax問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Java用split分割含一個(gè)或多個(gè)空格的字符串案例

    Java用split分割含一個(gè)或多個(gè)空格的字符串案例

    這篇文章主要介紹了Java用split分割含一個(gè)或多個(gè)空格的字符串案例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來過來看看吧
    2020-09-09
  • Java SpringMVC實(shí)現(xiàn)國際化整合案例分析(i18n)

    Java SpringMVC實(shí)現(xiàn)國際化整合案例分析(i18n)

    本篇文章主要介紹了Java SpringMVC實(shí)現(xiàn)國際化整合案例分析(i18n),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • springboot整合xxl-job的示例代碼

    springboot整合xxl-job的示例代碼

    這篇文章主要介紹了springboot整合xxl-job的示例代碼,主要分為三大模塊,分別是調(diào)度中心、執(zhí)行器和配置定時(shí)任務(wù)的過程,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06
  • java實(shí)戰(zhàn)之桌球小游戲

    java實(shí)戰(zhàn)之桌球小游戲

    這篇文章主要為大家詳細(xì)介紹了java實(shí)戰(zhàn)之桌球小游戲,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-07-07
  • 使用Java實(shí)現(xiàn)簡單搭建內(nèi)網(wǎng)穿透

    使用Java實(shí)現(xiàn)簡單搭建內(nèi)網(wǎng)穿透

    內(nèi)網(wǎng)穿透是一種網(wǎng)絡(luò)技術(shù),適用于需要遠(yuǎn)程訪問本地部署服務(wù)的場景,本文主要為大家介紹了如何使用Java實(shí)現(xiàn)簡單搭建內(nèi)網(wǎng)穿透,感興趣的可以了解下
    2024-02-02
  • Mybatis中如何使用sum對字段求和

    Mybatis中如何使用sum對字段求和

    這篇文章主要介紹了Mybatis中如何使用sum對字段求和,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 利用Spring Boot創(chuàng)建docker image的完整步驟

    利用Spring Boot創(chuàng)建docker image的完整步驟

    這篇文章主要給大家介紹了關(guān)于如何利用Spring Boot創(chuàng)建docker image的完整步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Java跳出當(dāng)前的多重嵌套循環(huán)的五種方法

    Java跳出當(dāng)前的多重嵌套循環(huán)的五種方法

    在Java編程中,跳出多重嵌套循環(huán)可以使用break語句、標(biāo)號與break組合、return語句、標(biāo)志變量和異常處理五種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-10-10

最新評論