Springboot 使用RestTemplate

超、凢脫俗 2022-12-22 09:21 478阅读 0赞

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

创建RestTemplate

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

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

设置请求头HttpHeaders

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

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

  1. public static final MediaType ALL = valueOf("*/*");
  2. public static final String ALL_VALUE = "*/*";
  3. public static final MediaType APPLICATION_ATOM_XML = valueOf("application/atom+xml");
  4. public static final String APPLICATION_ATOM_XML_VALUE = "application/atom+xml";
  5. public static final MediaType APPLICATION_FORM_URLENCODED = valueOf("application/x-www-form-urlencoded");
  6. public static final String APPLICATION_FORM_URLENCODED_VALUE = "application/x-www-form-urlencoded";
  7. public static final MediaType APPLICATION_JSON = valueOf("application/json");
  8. public static final String APPLICATION_JSON_VALUE = "application/json";
  9. public static final MediaType APPLICATION_JSON_UTF8 = valueOf("application/json;charset=UTF-8");
  10. public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
  11. public static final MediaType APPLICATION_OCTET_STREAM = valueOf("application/octet-stream");
  12. public static final String APPLICATION_OCTET_STREAM_VALUE = "application/octet-stream";
  13. public static final MediaType APPLICATION_PDF = valueOf("application/pdf");
  14. public static final String APPLICATION_PDF_VALUE = "application/pdf";
  15. public static final MediaType APPLICATION_RSS_XML = valueOf("application/rss+xml");
  16. public static final String APPLICATION_RSS_XML_VALUE = "application/rss+xml";
  17. public static final MediaType APPLICATION_XHTML_XML = valueOf("application/xhtml+xml");
  18. public static final String APPLICATION_XHTML_XML_VALUE = "application/xhtml+xml";
  19. public static final MediaType APPLICATION_XML = valueOf("application/xml");
  20. public static final String APPLICATION_XML_VALUE = "application/xml";
  21. public static final MediaType IMAGE_GIF = valueOf("image/gif");
  22. public static final String IMAGE_GIF_VALUE = "image/gif";
  23. public static final MediaType IMAGE_JPEG = valueOf("image/jpeg");
  24. public static final String IMAGE_JPEG_VALUE = "image/jpeg";
  25. public static final MediaType IMAGE_PNG = valueOf("image/png");
  26. public static final String IMAGE_PNG_VALUE = "image/png";
  27. public static final MediaType MULTIPART_FORM_DATA = valueOf("multipart/form-data");
  28. public static final String MULTIPART_FORM_DATA_VALUE = "multipart/form-data";
  29. public static final MediaType TEXT_EVENT_STREAM = valueOf("text/event-stream");
  30. public static final String TEXT_EVENT_STREAM_VALUE = "text/event-stream";
  31. public static final MediaType TEXT_HTML = valueOf("text/html");
  32. public static final String TEXT_HTML_VALUE = "text/html";
  33. public static final MediaType TEXT_MARKDOWN = valueOf("text/markdown");
  34. public static final String TEXT_MARKDOWN_VALUE = "text/markdown";
  35. public static final MediaType TEXT_PLAIN = valueOf("text/plain");
  36. public static final String TEXT_PLAIN_VALUE = "text/plain";
  37. public static final MediaType TEXT_XML = valueOf("text/xml");
  38. public static final String TEXT_XML_VALUE = "text/xml";
  39. private static final String PARAM_QUALITY_FACTOR = "q";

具体写法如下:

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

post请求

postForEntity

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

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

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

参数:

username: 张三

password: 123456

randomStr: 1597300142432

返回:

{

“code”: 200,

“msg”: “操作成功”,

“data”: {

“token”: “dfghjkl”,

“username”: “张三”,

},

“timestamp”: 1597299860

}

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

  1. Map<String,Object> jsonMap = new HashMap<>();
  2. jsonMap.put("com","ty");
  3. Map<String,Object> deMap = new HashMap<>();
  4. deMap.put("name", "设备");
  5. List<Object> list = new ArrayList<>();
  6. list.add(deMap);
  7. jsonMap.put("des",list);
  8. logger.info("----"+JSONObject.toJSONString(jsonMap));
  9. HttpEntity<String> httpEntitys = new HttpEntity<>(JSONObject.toJSONString(jsonMap),requestHeader);
  10. ResponseEntity<String> exchanges = restTemplate.postForEntity(url, httpEntitys, String.class);
  11. String resultRemote = exchanges.getBody();
  12. Map stringToMap = JSONObject.parseObject(resultRemote);

例子:

{

  1. des": \[\{
  2. "name": "设备"
  3. \}\],

“com”: “ty”

}

返回:

{

“code”: 200,

“msg”: “操作成功”,

“data”: “567897890-090”,

“timestamp”: 2367301740

}

Get请求

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

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

getForEntity请求带参数

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

get请求带请求头 exchange

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

PUT请求

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

DELETE 请求

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

exchange方法

post请求

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

get请求

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

put请求

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

delete请求

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

发表评论

表情:
评论列表 (有 0 条评论,478人围观)

还没有评论,来说两句吧...

相关阅读