Spring boot 发起http请求的简单用法

java后端发起http请求的方法经过不断演化(HttpURLConnection->HttpClient->CloseableHttpClient->RestTemplate),变得越来越简单方便。
Spingboot项目通过下面的配置,即可直接注入使用restTemplate很方便地发起http请求。

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
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
RestTemplate template = new RestTemplate(factory);
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); //避免中文乱码
List<HttpMessageConverter<?>> list= new ArrayList<HttpMessageConverter<?>>();
list.add(stringHttpMessageConverter);
template.setMessageConverters(list);
return template;
}

@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}

调用restTemplate.getXXX()或postXXX()等方法即可发起对应Method的http请求。特殊的请求头和请求体可以在request参数里使用HttpEntity。如调用下面这个方法可以把data封装成xml请求:

1
2
3
4
5
6
HttpEntity<String> genXmlRequest(Object data) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
String body = XmlUtils.stringify(data, "xml");
return new HttpEntity<String>(body, headers);
}