springboot-1-restTemplate的使用
2018-01-11 00:00
741 查看
原博客: http://blog.csdn.net/u013895412/article/details/53096855
核心代码:
请求测试:
也可以异步调用
自定义header
{ "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tomcatandjerry/p/5899722.html" }
核心代码:
String url = "http://localhost:8080/json"; JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
@Value("${Crawler_port.crawlerTotle}") private String crawlerTotle;//地址配置在xml文件里
String pingtaitongji = restTemplate.getForObject(crawlerTotle,String.class);
实用:
restConfig.javapackage com.iwhere.scrapy.rest; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 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.RestOperations; import org.springframework.web.client.RestTemplate; /** * 定义restTemplate的配置 * * @author wenbronk * @Date 下午4:33:35 */ @Configuration public class RestTemplateConfig { @Bean @ConditionalOnMissingBean({ RestOperations.class, RestTemplate.class }) public RestTemplate restTemplate(ClientHttpRequestFactory factory) { // return new RestTemplate(factory); RestTemplate restTemplate = new RestTemplate(factory); // 使用 utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为"ISO-8859-1") List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters(); Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator(); while (iterator.hasNext()) { HttpMessageConverter<?> converter = iterator.next(); if (converter instanceof StringHttpMessageConverter) { iterator.remove(); } } messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); return restTemplate; } @Bean @ConditionalOnMissingBean({ClientHttpRequestFactory.class}) public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setReadTimeout(15000);// ms factory.setConnectTimeout(15000);// ms return factory; } }
请求测试:
SpringRestTemplateApp.java
@RestController
@EnableAutoConfiguration
@Import(value = {Conf.class})
public class SpringRestTemplateApp {
@Autowired
RestTemplate restTemplate;
/***********HTTP GET method*************/
@RequestMapping("")
public String hello(){
String url = "http://localhost:8080/json"; JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
return json.toJSONString();
}
@RequestMapping("/json")
public Object genJson(){
JSONObject json = new JSONObject();
json.put("descp", "this is spring rest template sample");
return json;
}
/**********HTTP POST method**************/
@RequestMapping("/postApi")
public Object iAmPostApi(@RequestBody JSONObject parm){
System.out.println(parm.toJSONString());
parm.put("result", "hello post");
return parm;
}
@RequestMapping("/post")
public Object testPost(){
String url = "http://localhost:8080/postApi";
JSONObject postData = new JSONObject();
postData.put("descp", "request for post");
JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
return json.toJSONString();
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringRestTemplateApp.class, args);
}
}
也可以异步调用
@RequestMapping("/async") public String asyncReq(){ String url = "http://localhost:8080/jsonAsync"; ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class); future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() { public void onSuccess(ResponseEntity<JSONObject> result) { System.out.println(result.getBody().toJSONString()); } }, new FailureCallback() { public void onFailure(Throwable ex) { System.out.println("onFailure:"+ex); } }); return "this is async sample";
自定义header
@RequestMapping("/headerApi")//模拟远程的restful API public JSONObject withHeader(@RequestBody JSONObject parm, HttpServletRequest req){ System.out.println("headerApi====="+parm.toJSONString()); Enumeration<String> headers = req.getHeaderNames(); JSONObject result = new JSONObject(); while(headers.hasMoreElements()){ String name = headers.nextElement(); System.out.println("["+name+"]="+req.getHeader(name)); result.put(name, req.getHeader(name)); } result.put("descp", "this is from header"); return result; } @RequestMapping("/header") public Object postWithHeader(){ //该方法通过restTemplate请求远程restfulAPI HttpHeaders headers = new HttpHeaders(); headers.set("auth_token", "asdfgh"); headers.set("Other-Header", "othervalue"); headers.setContentType(MediaType.APPLICATION_JSON); JSONObject parm = new JSONObject(); parm.put("parm", "1234"); HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers); HttpEntity<String> response = restTemplate.exchange( "http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是string return response.getBody(); }
相关文章推荐
- springboot中配置restTemplate及简单使用
- 在spring boot中使用restTemplate上传大文件Java heap space
- Spring Boot使用RestTemplate消费REST服务的几个问题记录
- Spring Boot中RestTemplate的使用
- spring boot RestTemplate 发送 get 请求使用误区
- 使用RestTemplate消费spring boot的Restful服务
- SpringBoot系列十一:SpringBoot整合Restful架构(使用 RestTemplate 模版实现 Rest 服务调用、Swagger 集成、动态修改日志级别)
- springboot restTemplate使用以及相关配置
- spring boot / cloud (八) 使用RestTemplate来构建远程调用服务
- Spring boot 发送http请求组件RestTemplate使用实例
- springboot-24-restTemplate的使用
- Spring-boot RestTemplate 使用 报错问题
- spring boot / cloud (八) 使用RestTemplate来构建远程调用服务
- springboot使用restTemplate post提交值 restTemplate post值
- springboot 注入 restTemplate
- Spring Boot使用过滤器和拦截器分别实现REST接口简易安全认证
- 记录在Spring-Boot中使用Fegin调用RESTfull的PATCH方法设置
- SpringBoot通过restTemplate实现消费服务
- Spring Boot项目@RestController使用重定向redirect
- Spring使用RestTemplate模拟form提交示例