前言: 在我们用springboot 开发项目的过程用,会有调用第三方http接口的情况,这时我们使用spring的RestTemplate,使用更方便。
1,我们可以自己看下RestTemplate源码,提供了好多请求格式,你可以自己选择使用。具体方法说明网上都有,常用的getForEntity,getForObject,postForObject,postForEntity,exchange
2,如何在springboot中使用:
第一步:写配置加载类 RestTemplateConfig.java
直接上代码
import com.newcapec.shuttlebus.utils.HttpRequestUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.nio.charset.Charset;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.getMessageConverters().set(1,
new StringHttpMessageConverter(Charset.forName("UTF-8")));
restTemplate.setErrorHandler(new ThrowErrorHandler());
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(10000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
/**
* 注入封装RestTemplate
* @Title: httpRequestUtils
* @return httpRequestUtils
*/
@Bean(name = "httpRequestUtils")
public HttpRequestUtils httpRequestUtils(RestTemplate restTemplate) {
HttpRequestUtils httpRequestUtils = new HttpRequestUtils();
httpRequestUtils.setRestTemplate(restTemplate);
return httpRequestUtils;
}
class ThrowErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
//返回false表示不管response的status是多少都返回没有错
//这里可以自己定义那些status code你认为是可以抛Error
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
System.out.println("================>" + response.getBody());
//这里面可以实现你自己遇到了Error进行合理的处理
}
}
}
第二步:第一步中 我这里将restTemplate封装到了一个工具类里httpRequestUtils并注入到spring工厂里 ,下边把这个工具http请求的工具类发出来:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
public class HttpRequestUtils {
protected static final transient Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtils.class);
private RestTemplate restTemplate;
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String sendHttpRequestForm(String url, MultiValueMap<String, String> params) throws IOException {
LOGGER.debug("sendHttpRequestForm:{}", params.toString()); // 打印结果页面
HttpHeaders headers = new HttpHeaders();
// 提交方式表单提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
// 执行HTTP请求
try{
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
if(response.getStatusCode().isError()){
return "error";
}
return response.getBody();
}catch (Exception e){
e.printStackTrace();
}
return "error";
}
}
第三步:使用,上代码
// 加载
@Autowired
private HttpRequestUtils httpRequestUtils;
// 调用
String result = httpRequestUtils.sendHttpRequestForm(serviceURL, maps);
注意:maps这个参数是 MultiValueMap 类型的,serviceURL是请求的http地址
3,开发完成,可以测试了。