Springboot 使用RestTemplate

最近项目中springboot使用了RestTemplate,在此了解和学习了一下,有问题请指正

创建RestTemplate 

//自创建RestTemplate  public static RestTemplate restTemplate() {         SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();         requestFactory.setConnectTimeout(30000);// 设置连接超时,单位毫秒         requestFactory.setReadTimeout(30000);  //设置读取超时         RestTemplate restTemplate = new RestTemplate();         restTemplate.setRequestFactory(requestFactory);         logger.info("RestTemplate初始化完成");         return restTemplate;     }    //使用注解注入 @Autowired private  RestTemplate restTemplate;

引用的是spring-web-4.3.6.RELEASE.jar

设置请求头HttpHeaders

请求头中常设置的参数是Content-Type,一般用setContentType(MediaType mediaType)方式添加MediaType类中存在的值,或者用add(name,value)的方式添加所需要的值

MediaType类关于具体值的源码如下:

public static final MediaType ALL = valueOf("*/*");     public static final String ALL_VALUE = "*/*";     public static final MediaType APPLICATION_ATOM_XML = valueOf("application/atom+xml");     public static final String APPLICATION_ATOM_XML_VALUE = "application/atom+xml";     public static final MediaType APPLICATION_FORM_URLENCODED = valueOf("application/x-www-form-urlencoded");     public static final String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded";     public static final MediaType APPLICATION_JSON = valueOf("application/json");     public static final String APPLICATION_JSON_VALUE = "application/json";     public static final MediaType APPLICATION_JSON_UTF8 = valueOf("application/json;charset=UTF-8");     public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";     public static final MediaType APPLICATION_OCTET_STREAM = valueOf("application/octet-stream");     public static final String APPLICATION_OCTET_STREAM_VALUE = "application/octet-stream";     public static final MediaType APPLICATION_PDF = valueOf("application/pdf");     public static final String APPLICATION_PDF_VALUE = "application/pdf";     public static final MediaType APPLICATION_RSS_XML = valueOf("application/rss+xml");     public static final String APPLICATION_RSS_XML_VALUE = "application/rss+xml";     public static final MediaType APPLICATION_XHTML_XML = valueOf("application/xhtml+xml");     public static final String APPLICATION_XHTML_XML_VALUE = "application/xhtml+xml";     public static final MediaType APPLICATION_XML = valueOf("application/xml");     public static final String APPLICATION_XML_VALUE = "application/xml";     public static final MediaType IMAGE_GIF = valueOf("image/gif");     public static final String IMAGE_GIF_VALUE = "image/gif";     public static final MediaType IMAGE_JPEG = valueOf("image/jpeg");     public static final String IMAGE_JPEG_VALUE = "image/jpeg";     public static final MediaType IMAGE_PNG = valueOf("image/png");     public static final String IMAGE_PNG_VALUE = "image/png";     public static final MediaType MULTIPART_FORM_DATA = valueOf("multipart/form-data");     public static final String MULTIPART_FORM_DATA_VALUE = "multipart/form-data";     public static final MediaType TEXT_EVENT_STREAM = valueOf("text/event-stream");     public static final String TEXT_EVENT_STREAM_VALUE = "text/event-stream";     public static final MediaType TEXT_HTML = valueOf("text/html");     public static final String TEXT_HTML_VALUE = "text/html";     public static final MediaType TEXT_MARKDOWN = valueOf("text/markdown");     public static final String TEXT_MARKDOWN_VALUE = "text/markdown";     public static final MediaType TEXT_PLAIN = valueOf("text/plain");     public static final String TEXT_PLAIN_VALUE = "text/plain";     public static final MediaType TEXT_XML = valueOf("text/xml");     public static final String TEXT_XML_VALUE = "text/xml";     private static final String PARAM_QUALITY_FACTOR = "q";

 具体写法如下:

HttpHeaders headers = new HttpHeaders(); //相当于headers.add("Content-Type","application/json;charset=UTF-8"); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); 或者添加MediaType类没有的值 headers.add("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

post请求

postForEntity

如果请求参数是form-data类型的可以如下写法:

String url = "http://127.0.0.1:8080/login"; LinkedMultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(); paramMap.add("username", "zhangsan"); paramMap.add("password", "123456"); paramMap.add("randomStr",String.valueOf(System.currentTimeMillis())); HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, requestHeaders);  ResponseEntity<String> exchange = restTemplate.postForEntity(url, httpEntity, String.class);  String resultRemote = exchange.getBody();//得到返回的值 

具体的请求参数和返回的参数样例如下:

参数:

username: 张三

password: 123456

randomStr: 1597300142432

返回:

{

"code": 200,

"msg": "操作成功",

"data": {

"token": "dfghjkl",

"username": "张三",

},

"timestamp": 1597299860

}

如果请求参数是json,而且里面还有json数组

Map<String,Object> jsonMap = new HashMap<>(); jsonMap.put("com","ty"); Map<String,Object> deMap = new HashMap<>(); deMap.put("name", "设备"); List<Object> list = new ArrayList<>(); list.add(deMap); jsonMap.put("des",list); logger.info("----"+JSONObject.toJSONString(jsonMap));  HttpEntity<String>  httpEntitys = new HttpEntity<>(JSONObject.toJSONString(jsonMap),requestHeader); ResponseEntity<String> exchanges = restTemplate.postForEntity(url, httpEntitys, String.class);  String resultRemote = exchanges.getBody(); Map stringToMap = JSONObject.parseObject(resultRemote);

例子:

{

    des": [{

            "name": "设备"

         }],

"com": "ty"

}

返回:

{

"code": 200,

"msg": "操作成功",

"data": "567897890-090",

"timestamp": 2367301740

}

 

Get请求

getForEntity请求不带参数,默认请求头

//请求不带参数,默认请求头 String url = "xxx.xx.xx"; ResponseEntity<String> result = restTemplate.getForEntity(url,String.class);   

getForEntity请求带参数

//URL作为String String url = "http://127.0.0.1:8080/login?name={name}"; Map<String,String> map = new HashMap<>(); map.put("name","张三"); ResponseEntity<String> result = restTemplate.getForEntity(url,String.class,map);  //URL作为URI,参数存进URI中 UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build().expand("李四").encode(); URI uri = uriComponents.toUri(); ResponseEntity<String> result = restTemplate.getForEntity(uri,String.class);   //返回参数也可以是自定义对象例如User String url = "http://127.0.0.1:8080/login?name={name}"; Map<String,String> map = new HashMap<>(); map.put("name","张三"); ResponseEntity<User> result = restTemplate.getForEntity(url,User.class,map); 

get请求带请求头 exchange

HttpHeaders resultRequestHeader = new HttpHeaders(); resultRequestHeader.add("Authorization", "wetyuigyihjj"); resultRequestHeader.add("charset", "UTF-8"); resultRequestHeader.setContentType(MediaType.APPLICATION_JSON); LinkedMultiValueMap<String, Object> resultParamMap = new LinkedMultiValueMap<>();  HttpEntity<String>  resultHttpEntity = new HttpEntity<>(null, resultRequestHeader); ResponseEntity<String> exchange = restTemplate.exchange(resultUrl, HttpMethod.GET,resultHttpEntity,String.class);  resultRemote = exchange.getBody(); logger.info("结果resultRemote:"+resultRemote); Map stringToMap = JSONObject.parseObject(resultRemote);

PUT请求

//put方法的参数和postForEntity方法的参数基本一致 String url = "http://127.0.0.1:8080/login"; Map<String,Object> jsonMap = new HashMap<>(); jsonMap.put("username","admin"); jsonMap.put("password","123456"); HttpEntity<String>  httpEntitys = new HttpEntity<>(JSONObject.toJSONString(jsonMap),requestHeaders);  restTemplate.put(url,httpEntitys,String.class);

 

DELETE 请求

String url = "http://127.0.0.1:8080/get?name={name}"; restTemplate.delete(url,"张三");

 

exchange方法

post请求

String url = "http://127.0.0.1:8080/login"; LinkedMultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(); paramMap.add("username", "zhangsan"); paramMap.add("password", "123456"); paramMap.add("randomStr",String.valueOf(System.currentTimeMillis())); HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, requestHeaders);  ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST,httpEntitys,String.class);  String resultRemote = exchange.getBody();//得到返回的值
 

get请求

ResponseEntity<String> exchange = restTemplate.exchange(resultUrl, HttpMethod.GET,resultHttpEntity,String.class);  或者  ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET,null,String.class);

 

put请求

String url = "http://127.0.0.1:8080/login"; LinkedMultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>(); paramMap.add("username", "zhangsan"); paramMap.add("password", "123456"); paramMap.add("randomStr",String.valueOf(System.currentTimeMillis())); HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(paramMap, requestHeaders);  ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.PUT,httpEntitys,String.class);

delete请求

String url = "http://127.0.0.1:8080/get"; ResponseEntity<String> result = restTemplate.exchange(url + "?id={id}", HttpMethod.DELETE, null, String.class, 56789);