HttpRestClient.java
3.15 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.ui.http;
import com.ui.config.SystemConfig;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class HttpRestClient {
private static final Logger logger = LoggerFactory
.getLogger(HttpRestClient.class);
private RestTemplate restTemplate;
private SystemConfig systemConfig;
public <T> T defaultPost(String uri, Object request, Class<T> responseType) {
try {
return restTemplate.postForObject(systemConfig.getServiceUrl() + uri, request,responseType);
} catch (Exception e) {
logger.error("postForObject failed!url:"+uri, e);
return null;
}
}
public <T> T defaultGet(String uri, Class<T> responseType,Map<String, ?> map) {
try {
StringBuilder url = new StringBuilder(uri);
if(map != null){
url.append("?");
for (Map.Entry<String, ?> entry : map.entrySet()) {
url.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
return restTemplate.getForObject(systemConfig.getServiceUrl() + url.toString().substring(0, url.length()-1), responseType);
}
return restTemplate.getForObject(systemConfig.getServiceUrl() + uri, responseType);
} catch (Exception e) {
logger.error("getForObject failed!url: "+uri, e);
return null;
}
}
public <T> T get(String url, Class<T> responseType,Map<String, ?> map) {
try {
StringBuilder uri = new StringBuilder(url);
if(map != null){
uri.append("?");
for (Map.Entry<String, ?> entry : map.entrySet()) {
uri.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
return restTemplate.getForObject(uri.toString().substring(0, uri.length()-1), responseType);
}
return restTemplate.getForObject(url, responseType);
} catch (Exception e) {
logger.error("getForObject failed!url: "+url, e);
return null;
}
}
public <T> T post(String url, Object request, Class<T> responseType) {
try {
return restTemplate.postForObject(url, request,responseType);
} catch (Exception e) {
logger.error("postForObject failed!url:"+url, e);
return null;
}
}
public <T> T defaultGet(String uri, Class<T> responseType) {
try {
return restTemplate.getForObject(systemConfig.getServiceUrl() + uri, responseType);
} catch (Exception e) {
logger.error("getForObject failed!url: "+uri, e);
return null;
}
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void setSystemConfig(SystemConfig systemConfig) {
this.systemConfig = systemConfig;
}
}