restTemplate使用实例

请求携带cookie

        HttpHeaders headers = new HttpHeaders();
        List 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 response = restTemplate.postForEntity(url, request, String.class);

post表单

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap map = new LinkedMultiValueMap();
        map.add("title", title);
        map.add("desc", desc);
        map.add("userid", toUserId);
        HttpEntity> request = new HttpEntity>(map, headers);
        ResponseEntity 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 entity = new HttpEntity(requestJson, headers);
        ResponseEntity 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 entity = new HttpEntity(headers);
ResponseEntity response = restTemplate.exchange(url,HttpMethod.GET, entity, byte[].class);
byte[] imageBytes = response.getBody();

你可能感兴趣的:(springboot)