笔记是从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);
    }
    
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐