RestTemplate使用

自定义Http Header和HttpBody

GET请求

构造HttpHeaders对象,主要是安全验证

HttpHeaders headers = new HttpHeaders();
headers.add("Date", auth.get(0));
headers.add("Authorization", auth.get(1));

使用HttpHeaders对象构造HttpEntity:

HttpEntity request = new HttpEntity(headers);

发送GET请求
使用resttemplate.getForEntity是不能设置请求http头的,需要使用通用的请求方法resttemplate.exchange,并指定请求类型(GET请求类型)

ResponseEntity<String> responseEntity = restTemplate.exchange(host + url, HttpMethod.GET, request, String.class, vars);

POST请求

构造HttpHeaders对象,主要是安全验证

HttpHeaders headers = new HttpHeaders();
headers.add("Date", auth.get(0));
headers.add("Authorization", auth.get(1));

使用HttpHeaders对象构造HttpEntity:

HttpEntity request = new HttpEntity(jsondata.toString(),headers);

HttpEntity接收一个参数时,参数类型HttpHeaders,表示Http头,接收两个参数,第一个参数为HttpBody(http请求体),第二个HttpHeaders。

此处json对象一定记得转为字符串,不然会出现没有合适的HttpMessageConverter错误。

发送PSOT请求

ResponseEntity<String> responseEntity = restTemplate.postForEntity(host + url, request, String.class);

也可使用exchange方法发送post请求。

POST发送表单

  1. 设置Http头ContentType为MediaType.MULTIPART_FORM_DATA,表示表单的数据;

  2. 设置Http Body为具体表单数据。表单数据为Map类型。

  3. 使用RestTemplate发送post请求。

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.put("name", Arrays.asList("zhangsan")); formData.put("age", Arrays.asList("23")); formData.put("email", Arrays.asList("zhangsan@gmail.com")); HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, String>> requestHttp = new HttpEntity<MultiValueMap<String, String>>(formData, header); String response = restTemplate.postForObject("http://localhost:8080/person", requestHttp, String.class); System.out.println(response);

POST 文件上传

待整理

评论

暂无评论