欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用RestTemplate远程调用

程序员文章站 2022-04-28 16:52:39
...

使用RestTemplate远程调用

package com.test.demo7000.resttemplate;

import com.google.gson.JsonObject;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;

public class RestTemplateDemo4 {

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(60000))
                .setReadTimeout(Duration.ofSeconds(60000))
                .build();
		// header
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("module","***");
        headers.add("action","get***");
		// body
        JsonObject body= new JsonObject();
        body.addProperty("transaction_id", "***");
        body.addProperty("ebay_itemid", "***");
		// 整合参数
        HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);
        // url
        String url = "http://***";
        // post调用,返回String
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        // 返回结果
        System.out.println(result.getBody());
    }

}