[关闭]
@TedZhou 2020-10-15T08:45:04.000000Z 字数 1675 阅读 344

Springboot 发起http请求的简单用法

java spring


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

  1. import java.nio.charset.Charset;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.http.client.ClientHttpRequestFactory;
  7. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  8. import org.springframework.http.converter.HttpMessageConverter;
  9. import org.springframework.http.converter.StringHttpMessageConverter;
  10. import org.springframework.web.client.RestTemplate;
  11. @Configuration
  12. public class RestTemplateConfig {
  13. @Bean
  14. public RestTemplate restTemplate(ClientHttpRequestFactory factory){
  15. RestTemplate template = new RestTemplate(factory);
  16. StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); //避免中文乱码
  17. List<HttpMessageConverter<?>> list= new ArrayList<HttpMessageConverter<?>>();
  18. list.add(stringHttpMessageConverter);
  19. template.setMessageConverters(list);
  20. return template;
  21. }
  22. @Bean
  23. public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
  24. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  25. factory.setConnectTimeout(15000);
  26. factory.setReadTimeout(5000);
  27. return factory;
  28. }
  29. }

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

  1. HttpEntity<String> genXmlRequest(Object data) {
  2. HttpHeaders headers = new HttpHeaders();
  3. headers.setContentType(MediaType.APPLICATION_XML);
  4. String body = XmlUtils.stringify(data, "xml");
  5. return new HttpEntity<String>(body, headers);
  6. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注