Java笔记-使用RestTemplate发送http数据包(get与post)
生活随笔
收集整理的這篇文章主要介紹了
Java笔记-使用RestTemplate发送http数据包(get与post)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近看項目,方面大佬們都喜歡用RestTemplate去發送http報文,在此記錄下,方便下次使用
這里只舉get和post例子。
?
get例子。
程序運行截圖如下:
后臺:
源碼如下:
這里要先配置下config
代碼如下:
package cn.it1995.config;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate;@Configuration public class AppConfig {@Beanpublic RestTemplate restTemplate(){return new RestTemplate();} }get方式源碼如下:
MyController.java
package cn.it1995.controller;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate;@RestController public class MyController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("/getMsg")public Object sendMsg(@RequestParam("msg") String msg){ResponseEntity<String> forEntity = restTemplate.getForEntity(msg, String.class);System.out.println("------------head start------------");System.out.println(forEntity.getHeaders());System.out.println("------------head end------------");System.out.println("------------body start------------");System.out.println(forEntity.getBody());System.out.println("------------body end------------");System.out.println("\n\n");return null;} }下面是另外一個開源程序的例子,在此我直接貼下代碼,post請求
@PostMapping("/loginByQQ")public Object loginByQQ(String token, HttpServletResponse response, HttpServletRequest request){MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap();paramMap.add("token", token);ResponseEntity<Object> objectResponseEntity = restTemplate.postForEntity("http://127.0.0.7:8081/getLoginInfo", paramMap, Object.class);Object body = objectResponseEntity.getBody();String uuid = CookieUtil.setLoginCookie(request, response);//json標準化String newJson = body.toString().replace("=", ":");System.out.println(newJson);Map map = JSON.parseObject(newJson, Map.class);Map data = JSON.parseObject(map.get("data").toString(), Map.class);user.put(uuid, data);return Result.success();}?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Java笔记-使用RestTemplate发送http数据包(get与post)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++笔记-基于邻接矩阵的BFS(宽度优
- 下一篇: QtJava笔记-Qt与Java进行SS