嗷嗷待哺的controller(被調用provider的controller方法)
//測試get少量參數 @RequestMapping(value = "detailsGetD",method = RequestMethod.GET) public String test05(Integer id,String name){ System.out.println("GET-"+id+"-"+name); return "error"; } //測試post @RequestMapping(value = "detailsPostD",method = RequestMethod.POST) public String test06(Integer id,String name){ System.out.println("POST-"+id+"-"+name); return "error"; } //測試put @RequestMapping(value = "detailsPutD",method = RequestMethod.PUT) public String test07(Integer id,String name){ System.out.println("PUT-"+id+"-"+name); return "error"; } //測試delete @RequestMapping(value = "detailsDeleteD",method = RequestMethod.DELETE) public String test08(Integer id,String name){ System.out.println("DELETE-"+id+"-"+name); return "error"; }
consumer的調用傳參(url拼接少量參數)
//get傳遞單參 ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsGetD?id={id}&name={name}", HttpMethod.GET, null, String.class,1,"zsw"); //post傳遞單參 ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPostD?id={id}&name={name}", HttpMethod.POST, null, String.class,1,"zsw"); //put傳遞單參 Map<String,Object> map=new HashMap<>(); map.put("id",1); map.put("name","zsw"); ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPutD?id={id}&name={name}", HttpMethod.PUT, null, String.class,map); //delete傳遞單參 Map<String,Object> map=new HashMap<>(); map.put("id",1); map.put("name","zsw"); ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsDeleteD?id={id}&name={name}", HttpMethod.DELETE, null, String.class,map); //返回內容 String result = resp.getBody(); System.out.println(result);
使用map和直接寫參數都可以。
再介紹一下傳json對象。
首先登場的是provider方controller。
//測試get @RequestMapping(value = "detailsGet",method = RequestMethod.GET) public String test01(@RequestBody Detail detail){ System.out.println("GET-"+detail); return "error"; } //測試post @RequestMapping(value = "detailsPost",method = RequestMethod.POST) public String test02(@RequestBody Detail detail){ System.out.println("POST-"+detail); return "error"; } //測試put @RequestMapping(value = "detailsPut",method = RequestMethod.PUT) public String test03(@RequestBody Detail detail){ System.out.println("PUT-"+detail); return "error"; } //測試delete @RequestMapping(value = "detailsDelete",method = RequestMethod.DELETE) public String test04(@RequestBody Detail detail){ System.out.println("DELETE-"+detail); return "error"; }
我們再來看consumer的選手,傳參json對象。
String json = "{\"author\":\"zsw\",\"createdate\":1582010438846,\"id\":1,\"summary\":\"牡丹\",\"title\":\"菏澤\"}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(json,headers); ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPost", HttpMethod.POST, entity, String.class); HttpStatus statusCode = resp.getStatusCode(); // 獲取響應碼 int statusCodeValue = resp.getStatusCodeValue(); // 獲取響應碼值 HttpHeaders headers1 = resp.getHeaders(); // 獲取響應頭 System.out.println("statusCode:" + statusCode); System.out.println("statusCodeValue:" + statusCodeValue); System.out.println("headers:" + headers1); //或者直接傳對象,底層自己處理 Detail detail=new Detail(); detail.setId(1L); detail.setSummary("牡丹"); detail.setTitle("菏澤"); detail.setAuthor("zsw"); detail.setCreatedate(new Timestamp(new Date().getTime())); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Detail> entity = new HttpEntity<>(detail,headers); ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsDelete", HttpMethod.DELETE, entity, String.class); //拿到返回值 String result = resp.getBody(); System.out.println(result); return result;
post、put、delete請求都可以用這種方法。但是測試get時就不行了直接報錯:org.springframework.web.client.HttpClientErrorException: 400 null(錯誤請求,服務器不理解請求的語法),get請求不支持這種方式的傳參,get請求只能將請求參數拼接URI
后邊,而不能單獨傳遞request body參數,除非你改用POST
。如果用resuful風格,必須要get傳參對象,也不是沒有辦法的。根據(https://blog.belonk.com/c/http_resttemplate_get_with_body.html)這篇文章,小弟把情況摸清楚了,上手!
import com.alibaba.fastjson.JSON; import com.github.pagehelper.PageInfo; import com.zhou.entity.Detail; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Repository; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; @Repository public class DetailMapper { public String test(){ RestTemplate restTemplate1 = new RestTemplate(); restTemplate1.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory()); String json = "{\"author\":\"zsw\",\"createdate\":1582010438846,\"id\":1,\"summary\":\"牡丹\",\"title\":\"菏澤\"}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(json,headers); ResponseEntity<String> resp = restTemplate1.exchange("http://localhost:8080/detailsGet", HttpMethod.GET, entity, String.class); String result = resp.getBody(); System.out.println(result); return result; } private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory { @Override protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { if (httpMethod == HttpMethod.GET) { return new HttpGetRequestWithEntity(uri); } return super.createHttpUriRequest(httpMethod, uri); } } private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase { public HttpGetRequestWithEntity(final URI uri) { super.setURI(uri); } @Override public String getMethod() { return HttpMethod.GET.name(); } } }
大致就是這個樣子。對於沒接觸過httpclient的我,有些類不能導包,屬實有的懵。百度百度百度。。。 找到httpclient的maven的依賴,下載導包,成功!啟動項目:無法訪問org.apache.http.annotation.ThreadSafe,找不到org.apache.http.annotation.ThreadSafe的類文件 ???,我記憶中沒有用過這個類,全局搜索一下也找不到(ctrl+shift+f - 查詢自己寫的代碼)。繼續百度,說httpclient4.5.2版本和httpcore4.4.4版本更配哦,maven自動下載的httpcore4.4.13,今天這個maven咋回事(好感-1),參考(https://www.jianshu.com/p/f35eac56c334)文章,最終的pom文件:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zhou</groupId> <artifactId>news-consumer</artifactId> <version>0.0.1-SNAPSHOT</version> <name>news-consumer</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 分頁 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.13</version> </dependency> <!-- Apache Commons IO --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <!-- Apache Commons IO --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
重新啟動,訪問,拿到參數。
附上github地址:https://github.com/wwck-zsw/RestTemplate
參考鏈接:
https://segmentfault.com/a/1190000021123356
https://www.cnblogs.com/jnba/p/10522608.html(靈感來源)