zoukankan      html  css  js  c++  java
  • (8)RestTemplate真实案例-copy

    1. 场景描述

    现在越来越的系统之间的交互采用http+json的交互方式,以前用的比较多的HttpClient,后来用的RestTemplate,感觉RestTemplate要比httpClent简洁的多,简单介绍下,项目中正在使用的get和post调用方式。

    2. 解决方案

    2.1 简要说明

    RestTemplate是集成在spring-web中的,因为springboot的starter已经默认加载进来,所以可以直接使用不用再配置maven的gav了。

    2.2 post调用方式

    2.2.1 真实代码
        public static String invoke(String url, HashMap params) throws Exception {
    
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(params), headers);
            
            RestTemplate rst = new RestTemplate();
            ResponseEntity<String> stringResponseEntity = rst.postForEntity(url, httpEntity, String.class);
    
            return stringResponseEntity.getBody();
        }
    
    2.2.2 代码说明

    invoke是通用方法调用,项目中的入参是:url和map,url是调用地址,写在配置文件中;map是外围系统需要的参数,在相关类中进行封装后传过来。

    2.3 get调用方式

    2.3.1真实代码
    	public JSONArray getUsers() throws Exception {
    		JSONArray result = new JSONArray();
    		try {
    			RestTemplate restTemplate = new RestTemplate();
    			result = restTemplate.getForObject(apiUrl + "/user/list?appCode={1}",
    					JSONArray.class, code);
    		} catch (Exception e) {
    		}
    		return result;
    	}
    
    2.3.2 代码说明

    其中参数是:url和code,根据code去查询对应集合。

    2.4 RestTemplate Api说明

      
    DELETE delete
    GET getForObject
      getForEntity
    HEAD headForHeaders
    OPTIONS optionsForAllow
    POST postForLocation
      postForObject
      postForEntity
    PUT put
    any exchange
      execute

    一般只需记住get与post的五个就可以了(getForObject 、getForEntity、postForLocation、postForObjec、postForEntity),这几个方法有很多重载的方法,参数不一样,可根据实际情况调用。

  • 相关阅读:
    angular js模块,angular js控制器
    select ipnut双向数据绑定用法
    ng-repeat循环遍历的用法
    angular js起步
    文件上传(预览2 老师提供的方法)
    设置mui头部(头部与最上面可以设置同样的样子)支持ios (苹果) 安卓不支持
    点击按钮btn 打开(跳转)新的页面
    定位精准 并打印出来
    把原始坐标转化为百度坐标(位置更精确)
    原始地理定位
  • 原文地址:https://www.cnblogs.com/hanease/p/14520552.html
Copyright © 2011-2022 走看看