`
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Collections;
/**
*RestTemplate工具类
*
*/
public class RestTemplateUtils {
public static Object getHttpUrlEncodeRequest(String url, Object request) {
Object result = null;
//设置代理
RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory() {
{
setProxy(new java.net.Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname", Integer.parseInt("8080"))));
}
});
//设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
//请求格式,可以设置别的类型urlencoded类型在请求时会自动将请求参数进行urlencode不用事先进行处理。
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//设置参数,请求体可以为Sring,json等类型
MultiValueMap<String,Object> params=new LinkedMultiValueMap<>();
params.put("id", Collections.singletonList(request));
HttpEntity<Object> objectHttpEntity = new HttpEntity<>(params, httpHeaders);
try {
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.POST, objectHttpEntity, Object.class);
result = response.getBody();
int code = response.getStatusCodeValue();
} catch (RestClientException e) {
e.printStackTrace();
}
return result;
}
public static Object getHttpJsonRequest(String url, Object request) {
Object result = null;
//设置代理
RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory() {
{
setProxy(new java.net.Proxy(Proxy.Type.HTTP, new InetSocketAddress("hostname", Integer.parseInt("8080"))));
}
});
//设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
//请求格式,可以设置别的类型
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
//设置请求体,请求体可以为Sring,json等类型
HttpEntity<Object> objectHttpEntity = new HttpEntity<>(request, httpHeaders);
try {
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.POST, objectHttpEntity, Object.class);
result = response.getBody();
int code = response.getStatusCodeValue();
} catch (RestClientException e) {
e.printStackTrace();
}
return result;
}
}
`