restTemplate使用实例
博客专区 > go4it 的博客 > 博客详情
restTemplate使用实例
go4it 发表于10个月前
restTemplate使用实例
  • 发表于 10个月前
  • 阅读 31
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云实验室 1小时搭建人工智能应用,让技术更容易入门 免费体验 >>>   

##请求携带cookie

        HttpHeaders headers = new HttpHeaders();
        List<String> cookies = new ArrayList<>();
        cookies.add("JSESSIONID=" + Strings.nullToEmpty(jsessionId));
        cookies.add("token=" + Strings.nullToEmpty(token));
        headers.put(HttpHeaders.COOKIE,cookies);
        HttpEntity request = new HttpEntity(null, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

##post表单

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("title", title);
        map.add("desc", desc);
        map.add("userid", toUserId);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

##post json

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
    ResponseEntity<String> resp = restTemplate.postForEntity(url,entity,String.class);

##url post

                String template = baseUrl + "/demo?app={0}&userId={1}";
                String url = MessageFormat.format(template,app,userId);
                return restTemplate.postForEntity(url,null,String.class);

##请求图片

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(url,HttpMethod.GET, entity, byte[].class);
byte[] imageBytes = response.getBody();
标签: Spring Boot
共有 人打赏支持
粉丝 13
博文 392
码字总数 185562
×
go4it
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: