SpringBoot HTTPS 远程调用接口:POST 请求参数在 Body 中
在 Spring Boot 中使用 HTTPS 远程调用别人的接口,可以使用'RestTemplate'来发送 POST 请求,并将参数放到请求的 body 里面。以下是一个示例代码:
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class HttpsRemoteCall {
public static void main(String[] args) {
// 创建RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 设置请求参数
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("param1", "value1");
params.add("param2", "value2");
// 创建请求体
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
// 发送POST请求
ResponseEntity<String> responseEntity = restTemplate.exchange("https://example.com/api/endpoint", HttpMethod.POST, requestEntity, String.class);
// 获取响应数据
HttpStatus statusCode = responseEntity.getStatusCode();
String responseBody = responseEntity.getBody();
// 处理响应数据
if (statusCode == HttpStatus.OK) {
// 请求成功
System.out.println("Response body: " + responseBody);
} else {
// 请求失败
System.out.println("Request failed with status code: " + statusCode);
}
}
}
在上面的代码中,我们使用'RestTemplate'发送了一个 POST 请求,请求的 URL 是'https://example.com/api/endpoint',请求参数放在'MultiValueMap'对象中,并将其作为请求体传递给'HttpEntity'对象。在'HttpEntity'中,我们还设置了请求头的'Content-Type'为'application/json',可以根据实际情况调整。通过'RestTemplate'的'exchange'方法发送请求,并获取响应数据。最后根据响应的状态码进行相应的处理。
请注意,上述代码中使用的是'RestTemplate',它是以同步方式发送请求的。如果你需要以异步方式发送请求,可以考虑使用'AsyncRestTemplate'或者'WebClient'。
原文地址: https://www.cveoy.top/t/topic/qFfg 著作权归作者所有。请勿转载和采集!