java工具类中静态方法使用有设置超时时间连接时间等配置的RestTemplate
时间: 2024-02-05 20:14:18 浏览: 191
是的,Java中的RestTemplate工具类可以使用静态方法来发送HTTP请求。RestTemplate提供了一些配置选项,包括设置连接和读取超时时间、添加请求头等等。下面是一个示例代码:
```
public class RestTemplateUtil {
private static final int TIMEOUT = 5000;
private static final RestTemplate restTemplate = new RestTemplate();
static {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(TIMEOUT);
requestFactory.setReadTimeout(TIMEOUT);
restTemplate.setRequestFactory(requestFactory);
}
public static <T> T get(String url, Class<T> responseType) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, responseType);
return responseEntity.getBody();
}
public static <T> T post(String url, Object request, Class<T> responseType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(request, headers);
ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, responseType);
return responseEntity.getBody();
}
}
```
在上面的代码中,我们通过设置SimpleClientHttpRequestFactory来设置超时时间,然后使用RestTemplate发送HTTP请求。get和post方法分别用于发送GET和POST请求,并且可以指定返回类型。
阅读全文