【Java SE】http请求RestTemplate

【Java SE】http请求RestTemplate

RestTemplate对象

@Configuration
public class RestTemplateConfiguration {
    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(120 * 1000);
        httpRequestFactory.setConnectTimeout(2 * 60 * 1000);
        httpRequestFactory.setReadTimeout(10 * 60 * 1000);
        return new RestTemplate(httpRequestFactory);
    }
}

简单例子

public String getJsonDataFromUrl(String url, String method) {
    String json;
    if ("get".equals(method.toLowerCase())) {
        json = restTemplate.getForObject(url, String.class);
    } else {
        MultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
        if (url.contains("?")) {
            int index = url.indexOf("?");
            String paramStr = url.substring(index + 1);
            url = url.substring(0, index);
            String[] itemArray = paramStr.split("&");
            for (String item : itemArray) {
                String[] pairArray = item.split("=");
                request.add(pairArray[0], pairArray[1]);
            }
        }
        json = restTemplate.postForObject(url, request, String.class);
    }
    return json;
}

 

posted @ 2022-05-26 15:03  翠微  阅读(40)  评论(0编辑  收藏  举报