RestTemplate、HttpHeaders、HttpEntity<String>
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
public static String handelPost(String url, String body){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> formEntity = new HttpEntity<>(body, headers);
String str= restTemplate.postForEntity(url, formEntity, String.class).getBody();
return str;
}
HttpEntity和@RequestBody和@ResponseBody很像。除了能够访问请求和响应体,HttpEntity(和子类ResponseEntity)也能访问请求(和响应)头
@RequestMapping("/something")
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException
{ String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"); byte[] requestBody = requestEntity.getBody(); // do something with request header and body HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED); }
上面的例子获取MyRequestHeader请求头的值,读取请求体为字节数组。还把MyResponseHeader添加到响应中,把Hello World写到响应流中,并设置响应状态码为 201(创建)。
就像@RequestBody和@ResponseBody一样,Spring 使用HttpMessageConverter在请求和响应流之间进行转换。