RestTemplate 使用实例

Jul 19, 2018
package com.xy.plat;

import java.util.Collections;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class RestTempletTest {

    private static final Logger log = LoggerFactory.getLogger(RestTempletTest.class);

    private static final RestTemplate rest = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

    @Test
    public void Test() {
        {
            // http://www.baidu.com/?id=000
            ResponseEntity<String> entity = rest.getForEntity("http://www.baidu.com/?id={1}", String.class, "000");
            log.info(entity.getBody());
        }
        {
            // http://www.baidu.com/?id=ID
            ResponseEntity<String> entity = rest.getForEntity("http://www.baidu.com/?id={id}", String.class, Collections.singletonMap("id", "ID"));
            log.info(entity.getBody());
        }
        {
            // http://www.baidu.com/?id=789 -d {"name":"test"}
            // Content-Type: application/json;charset=UTF-8
            ResponseEntity<String> entity = rest.postForEntity("http://www.baidu.com/?id={1}", Collections.singletonMap("name", "test"), String.class, "789");
            log.info(entity.getBody());
        }
        {
            // http://www.baidu.com/?id=789 -d {"name":"test"}
            // Content-Type: application/json;charset=UTF-8
            String entity = rest.postForObject("http://www.baidu.com/?id={1}", Collections.singletonMap("name", "test"), String.class, "123");
            log.info(entity);
        }
        {
            // http://www.baidu.com/?id=789 -d
            // Content-Type: application/x-www-form-urlencoded
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            // ....
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("key", "value");
            HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<MultiValueMap<String, String>>(map, headers);
            String entity = rest.postForObject("http://www.baidu.com/?id={1}", req, String.class, "456");
            log.info(entity);
        }
        {
            // 注意参数不会做 URL编码
            // http://www.baidu.com/?id=? -d {"name":"test"}
            // Content-Type: application/json;charset=UTF-8
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("key", "value?");// 会错URL编码
            String entity = rest.postForObject("http://www.baidu.com/?id={1}", map, String.class, "?");
            log.info(entity);
        }
    }
}