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