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;
public class RestTemplatePostExample {
public static void main(String[] args) {
// 创建RestTemplate实例
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
// 构建请求体
String requestBody = "{\"name\":\"John\", \"age\":30}";
// 封装请求头和请求体
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
// 发送POST请求并获取响应
ResponseEntity<String> responseEntity = restTemplate.exchange(
"http://example.com/api/resource",
HttpMethod.POST,
requestEntity,
String.class
);
// 输出响应结果
System.out.println("Response status code: " + responseEntity.getStatusCode());
System.out.println("Response body: " + responseEntity.getBody());
}
}
创建RestTemplate实例:RestTemplate restTemplate = new RestTemplate();
RestTemplate 是 Spring 提供的一个同步的客户端 HTTP 库,用于简化与 HTTP 服务的交互。设置请求头:HttpHeaders headers = new HttpHeaders();
HttpHeaders 类来设置 HTTP 请求头,例如 Content-Type。构建请求体:String requestBody = "{\"name\":\"John\", \"age\":30}";
封装请求头和请求体:HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
HttpEntity 类将请求头和请求体封装在一起。发送POST请求并获取响应:restTemplate.exchange(...)
exchange 方法发送 POST 请求,并指定 URL、HTTP 方法、请求实体以及响应类型。输出响应结果:System.out.println(...)
下一篇:java 数组遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站