spring/springboot RestTemplate使用笔记

实现前端表单的提交请求

RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap map= new LinkedMultiValueMap();
    map.add("image_url", "http://image.renrenjiang.cn/uploads/channel/60/liteQrcode/qrcode.png");
    HttpEntity> request = new HttpEntity>(map, headers);
    ResponseEntity 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 entity = new HttpEntity(body.toString(), headers);
       // 拿到图片的方式
ResponseEntity img = restTemplate.exchange("http:xxxxxxxx"      HttpMethod.POST, entity, byte[].class);

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

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

普通get请求方式

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

你可能感兴趣的:(spring,boot)