springBoot使用 RestTemplate中get 和 post方式传递json参数的多种方法(各种情况都包含)

项目中使用restTemplate的时候总是容易找不到适配的方式  先综合各种使用场景整理如下:

方式一:post---请求json数据-携带请求头

   /**
     * post请求json数据(添加请求头)
     */
    public static  void test1(){
        RestTemplate restTemplate = new RestTemplate();
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String url = "http://localhost:8087/callBackFor";
        User student = new User("sansan",10);
        HttpEntity<User> entity = new HttpEntity<User>(student, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        String user = responseEntity.getBody();//{"msg":"调用成功!","code":1}
        System.out.println(user);
    }

方式二:post --json数据(添加请求头)并传递表单参数

   /**
     * post请求json数据(添加请求头)并传递表单参数
     */
    public static  void test2(){
         RestTemplate restTemplate = new RestTemplate();
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String url = "http://localhost:8087/callBackFor?id={id}";
        Map<String, String> params = new HashMap<String, String>();
        params.put("id", "123");
        User student = new User("sansan",10);
        HttpEntity<User> entity = new HttpEntity<User>(student, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class, params);
        String user = responseEntity.getBody();//{"msg":"调用成功!","code":1}
        System.out.println(user);
    }


/**
  * 上述方式的简化版本
  */
        String template = baseUrl + "/demo?app={0}&userId={1}";
        String url = MessageFormat.format(template,app,userId);
        return restTemplate.postForEntity(url,null,String.class);

方式三:post --请求携带cookie

 HttpHeaders headers = new HttpHeaders();
 List<String> cookies = new ArrayList<>();
 cookies.add("JSESSIONID=" + Strings.nullToEmpty(jsessionId));
 cookies.add("token=" + Strings.nullToEmpty(token));
 headers.put(HttpHeaders.COOKIE,cookies);
 HttpEntity request = new HttpEntity(null, headers);
 ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

方式四:post --表单提交

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
 map.add("title", title);
 map.add("desc", desc);
 map.add("userid", toUserId);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

方式五:restTemplate.exchange post请求json数据(添加请求头)并传递表单参数

   /**
     * restTemplate.exchange post请求json数据(添加请求头)并传递表单参数
     * exchange可以发送HttpMethod.POST,DELE,GET,PUT请求;
     */
    public static  void test3(){
        RestTemplate restTemplate = new RestTemplate();
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String url = "http://localhost:8087/callBackFor?id={id}";
        //params是url中出现的路径变量
        Map<String, String> params = new HashMap<String, String>();
        params.put("id", "123");
        User student = new User("sansan",10);
        //entity包含请求的对象和消息头;
        HttpEntity<User> entity = new HttpEntity<User>(student, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class, params);
        String user = responseEntity.getBody();//{"msg":"调用成功!","code":1}
        System.out.println(user);
    }

方式六:get方式请求图片

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(url,HttpMethod.GET, entity, byte[].class);
byte[] imageBytes = response.getBody();

方式七:post请求json数据(添加请求头) 直接传递jsonString数据

/**
     * post请求json数据(添加请求头)  直接传递jsonString数据
     */
    public static  void test4(){
        RestTemplate restTemplate = new RestTemplate();
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //也可以这样设置contentType
        //MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        //headers.setContentType(type);
        //加不加Accept都可以
        //headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        String url = "http://localhost:8087/callBackFor";
        User student = new User("sansan",19);
        String jsonString = JSONObject.toJSONString(student);
        System.out.println(jsonString);//{"age":10,"name":"sansan"}
        HttpEntity<String> entity = new HttpEntity<String>(jsonString, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, entity, String.class);
        String user = responseEntity.getBody();//{"msg":"调用成功!","code":1}
        System.out.println(user);
    }

  • 10
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值