RestTemplateHelper.java
1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.yohoufo.user.helper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import javax.annotation.Resource;
import java.net.URI;
import java.util.Map;
@Component
public class RestTemplateHelper {
private static Logger log = LoggerFactory.getLogger(RestTemplateHelper.class);
@Autowired
RestTemplate restTemplate;
/**
* 使用json格式调用post请求
*
* @param url
* @param params
* @return
*/
public <T> T postByJson(String url, Object params, Class<T> responseType) throws RuntimeException {
log.info("call post with url={}, params={}", url, params);
MultiValueMap<String, String> headers = new LinkedMultiValueMap();
headers.set("Content-Type", "application/json; charset=UTF-8");
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<Object> entity = new HttpEntity<>(params, headers);
T response = restTemplate.postForObject(url, entity, responseType);
return response;
}
}