笔记是从Spring的文档中自己整理和翻译的
HttpEntity:代表一个HTTP请求或响应实体,由headers和body组成;一般和RestTemplate一起使用
1、常见使用方式一:HTTP request
RestTemplate restTemplate = new RestTemplate();
//请求头
HttpHeaders headers = new HttpHeaders();
//设置body的类型:纯文本形式
headers.setContentType(MediaType.TEXT_PLAIN);
//第一个参数:body,第二个参数:headers
HttpEntity<String> entity = new HttpEntity<>("HelloWorld", headers);
//第一个参数:请求地址,第二个参数:一个HTTP请求
URI location = restTemplate.postForLocation("http://localhost:8080", entity);
2、常见使用方式二:HTTP response
RestTemplate restTemplate = new RestTemplate();
//第一个参数:URL地址,第二个参数:响应类型
HttpEntity<String> entity = restTemplate.getForEntity("http://localhost:8080", String.class);
//响应体
String body = entity.getBody();
//响应体类型
MediaType contentType = entity.getHeaders().getContentType();
3、使用方式三:在Spring MVC中使用,作为@Controller方法的返回值
@RequestMapping("/handle")
public HttpEntity<String> handle() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("MyResponseHeader", "MyValue"); //设置头信息
return new HttpEntity<String>("Helloworld", responseHeaders);
}


1002

被折叠的 条评论
为什么被折叠?



