spring/springboot RestTemplate使用笔记

实现前端表单的提交请求

RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("image_url", "http://image.renrenjiang.cn/uploads/channel/60/liteQrcode/qrcode.png");
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
    ResponseEntity<String> str = restTemplate.postForEntity( "http://www.cncounter.com/qrcode/ajax/parseurl.json", request , String.class );
    System.out.println(str.getBody());

实现body 对象请求

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
JSONObject body = new JSONObject();
body.put("path", "xxxxx");
HttpEntity<String> entity = new HttpEntity<String>(body.toString(), headers);
       // 拿到图片的方式
ResponseEntity<byte[]> img = restTemplate.exchange("http:xxxxxxxx"      HttpMethod.POST, entity, byte[].class);

       // 直接拿到返回值的方式

       ResponseEntity<byte[]> img = restTemplate.exchange("http:xxxxxxxx" HttpMethod.POST, entity, byte[].class);

普通get请求方式

RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> accessToken = restTemplate.exchange("http:xxxxx", HttpMethod.GET, null, String.class);
   JSONObject json = JSONObject.fromObject(accessToken.getBody());

猜你喜欢

转载自blog.csdn.net/qq_22978533/article/details/78739295