日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot-24-restTemplate的使用

發布時間:2025/6/15 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot-24-restTemplate的使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

項目中使用的是HttpClient, 后來改成springboot, 偶然間發現restTemplate

原博客:?http://blog.csdn.net/u013895412/article/details/53096855

{ "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();

?

實用:?

restConfig.java

package 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);// msfactory.setConnectTimeout(15000);// msreturn 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-24-restTemplate的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。