Springboot 使用RestTemplate

Springboot 使用RestTemplate最近项目中 springboot 使用了 RestTemplate 在此了解和学习了一下 有问题请指正 1 先学习最简单的使用创建 RestTemplate SimpleClient newSimpleCli requestFacto setConnectTi

最近项目中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", ""); 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:

randomStr: 32

返回:

{

“code”: 200,

“msg”: “操作成功”,

“data”: {

“token”: “dfghjkl”,

“username”: “张三”,

},

“timestamp”:

}

如果请求参数是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”: “-090”,

“timestamp”:

}

 

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",""); 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", ""); 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", ""); 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); 

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230201.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号