java 调用第三方http接口的方式RestTemplate

Posted 低调码农哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 调用第三方http接口的方式RestTemplate相关的知识,希望对你有一定的参考价值。

 

  早期的 HttpURLConnection 使用非常繁琐,得写很多代码实现一个简单的请求,而 HttpClient 简单很多,不过此种方法使用起来太过繁琐,需要进行各种序列化和反序列化。RestTemplate 进一步简化,它可以像OkHttp那样的写法,但是常见的请求基本一句代码就可以搞定。

  使用RestTemplate方法,pom.xml文件几乎不用添加配置

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

 

  • 创建配置类RestTemplateConfig
package com.resttemp.demo.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;
    }
}
  • 创建代理服务类
package com.resttemp.demo.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;
    }
}
  • controller层调用
package com.resttemp.demo.controller;

import com.resttemp.demo.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("https:/***ById?id=3");
          System.out.println(result);
          return result;

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

    @GetMapping("/doGetForObj1")
    public String doGetForObj1(){
        try{
            String result= aRestTemplate.doGetForObj1("https:/***ById?id=4");
        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();
        }
    }
}

  完整目录结构如下

  参考:https://www.jianshu.com/p/2a59bb937d21

以上是关于java 调用第三方http接口的方式RestTemplate的主要内容,如果未能解决你的问题,请参考以下文章

java如何使用http方式调用第三方接口?最好有代码~谢谢

java 调用第三方http接口的方式RestTemplate

java 调用天气接口 自动获取当天天气

java如何调用接口方式

基于java高德天气的接口调用

java调用第三方接口