SpringBoot使用RestTemplate调用第三方接口

SpringBoot使用RestTemplate调用第三方接口

创建项目结构

在这里插入图片描述

pom文件修改

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.11</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo1</name>
	<description>demo1</description>
	<properties>
		<java.version>1.8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
		<fastjson.version>1.2.47</fastjson.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>${fastjson.version}</version>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

config文件

package com.example.demo1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


@Configuration
public class RestTemplateConfig {

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

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

controller文件

package com.example.demo1.controller;

import com.example.demo1.proxy.ARestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/a")
public class AController {

    @Autowired
    private ARestTemplate aRestTemplate;


    @GetMapping("/doGetEnity1")
    public String doGetEnity1(){
        try{
            String result= aRestTemplate.doGetEnity1("http://www...?loginName=...&password=...");
            System.out.println(result);
            return result;

        }catch (Exception e){
            return e.getMessage();
        }
    }

    @GetMapping("/doGetForObj1")
    public String doGetForObj1(){
        try{
            String result= aRestTemplate.doGetForObj1("http://www...?loginName=...&password=...");
            System.out.println(result);
            return result;

        }catch (Exception e){
            return e.getMessage();
        }
    }

    @PostMapping("/doPostForEnity1")
    public String doPostForEnity1(){
        try{
            String result= aRestTemplate.doPostForEnity1("https:/***/Save");
            System.out.println("jsonobject:"+result);
            return  result;

        }catch (Exception e){
            return e.getMessage();
        }
    }

    @PostMapping("/doPostForObj1")
    public String doPostForObj1(){
        try {
            String result= aRestTemplate.doPostForObj1("https:/***/Save");
            System.out.println("jsonobject:"+result);
            return  result;
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @PostMapping("/doExchange")
    public String doExchange(){
        try {
            String result = aRestTemplate.doExchange("https:/***/Save");
            System.out.println("jsonobject:" + result);
            return result;
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}

proxy文件

package com.example.demo1.proxy;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@Service
public class ARestTemplate {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 以get方式请求第三方http接口 getForEntity
     * @param url
     * @return
     */
    public String doGetEnity1(String url){
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String riskmerchantself = responseEntity.getBody();
        return riskmerchantself;
    }

    /**
     * 以get方式请求第三方http接口 getForObject
     * 返回值返回的是响应体,省去了我们再去getBody()
     * @param url
     * @return
     */
    public String doGetForObj1(String url){
        String riskmerchantself = restTemplate.getForObject(url, String.class);
        return riskmerchantself;
    }

    /**
     * 以post方式请求第三方http接口 postForEntity
     * @param url
     * @return
     */
    public String doPostForEnity1(String url){
        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json;charset=utf-8");
        //设置请求参数
        Map<String, Object> postData = new HashMap<>();
        postData.put("merchant_name", "model1");
        //将请求头和请求参数设置到HttpEntity中
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(postData, httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
        String body = responseEntity.getBody();
        return body;
    }

    /**
     * 以post方式请求第三方http接口 postForEntity
     * @param url
     * @return
     */
    public String doPostForObj1(String url){
        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json;charset=utf-8");
        //设置请求参数
        Map<String, Object> postData = new HashMap<>();
        postData.put("merchant_name", "model1");
        //将请求头和请求参数设置到HttpEntity中
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(postData, httpHeaders);
        String body = restTemplate.postForObject(url, httpEntity, String.class);
        return body;
    }

    /**
     * exchange
     * @return
     */
    public String doExchange(String url){
        //header参数
        HttpHeaders headers = new HttpHeaders();
        String token = "qqqqq";
        headers.add("authorization", token);
        headers.setContentType(MediaType.APPLICATION_JSON);

        //放入body中的json参数
        JSONObject obj = new JSONObject();
        obj.put("merchant_name", "model exchange");
        //组装
        HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
        String body = responseEntity.getBody();
        return body;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值