zoukankan      html  css  js  c++  java
  • RestTemplate的基本使用

    getForObject  和 getForEntity  的区别

    getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject。

    ResponseEntity<T>是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。如果需要提取其中的部分属性的话直接从ResponseEntity中调用相应的方法即可。(具体方法见下图)

    注意:使用restTemplate发送请求的时候,url地址的开头必须是http:// .......    一定不能是 https:// ...........       

    1、RestTemplate发送get请求携带HttpHeaders信息、参数

    1 HttpHeaders httpHeaders= new HttpHeaders();
    2 httpHeaders.add("Host", "XXXX.XXXX.XXXX.XX");
    3 //这里如果需要传递参数的话,将参数封装在map集合中,写到下面式子中null的位置处
    4 HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);//这里将头信息封装进HttpEntity中,发送请求时用exchange代替getForObject()方法
    5 ResponseEntity<String> resEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, requestEntity, String.class);

    2、RestTemplate发送get请求携带参数(直接将具体的参数传递过去)

      方法一:(当String类型的url地址中有参数的位置,可以理解为占位符)

      

    1 RestTemplate restTemplate = new RestTemplate();
    2 ResponseEntity<String> res = restTemplate.getForEntity("http://localhost:8080/user/{id}", String.class, "1");

      方法二:(将参数封装到map集合中传递)

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id", 11);
    ResponseEntity<String> res = restTemplate.getForEntity(
    "http://localhost::8080/user/{id}", String.class, map);
    String body = res.getBody();//返回的ResponseEntity中包含了头信息,body信息,状态码等信息。

    3、RestTemplate发送get请求---不携带任何参数

    1 RestTemplate restTemplate = new RestTemplate();
    2 ResponseEntity<String> res = restTemplate.getForEntity("http://localhost:8080/user/{id}", String.class);

    4、RestTemplate发送Post请求----没有参数,没有HttpHeaders信息

    • 方法的第一参数表示要调用的服务的地址
    • 方法的第二个参数表示上传的参数
    • 方法的第三个参数表示返回的消息体的数据类型
    @RequestMapping("/book3")
    public Book book3() {
        Book book = new Book();
        book.setName("红楼梦");
        ResponseEntity<Book> responseEntity = restTemplate.postForEntity("http://HELLO-SERVICE/getbook2", book, Book.class);
        return responseEntity.getBody();
    }

    5、如果你只关注,返回的消息体,可以直接使用postForObject。用法和getForEntity一致。

    6、使用RestTemplate发送Post请求----携带HttpHeaders信息,携带参数。

    HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.add("Host", "XXXX.XXXX.XXXX.XX");
    Map param = new HashMap();
    param.put("username","lisi");
    HttpEntity<HashMap> requestEntity = new HttpEntity<HashMap>(map, httpHeaders);
    String result
    = restTemplate.postForObject(url, requestEntity, String.class);
  • 相关阅读:
    OOP、DI、IOC的情爱恩仇录
    NuGet:添加EntityFramework
    DataGrid之DataGridComboBoxColumn,DataGridCheckBoxColumn,DataGridHyperlinkColumn,DataGridTextColumn
    JohnSon:动态创建模块选项卡
    maf实例
    MVVM理解之逐步重构成为MVVM模式,比MVC的独到之处
    我学Unity系列1:Unity和Mef的比较
    微软一站式代码资料
    匿名方法,泛型委托,Lambda表达式
    关于JS表单验证(转)
  • 原文地址:https://www.cnblogs.com/vegetableDD/p/11619390.html
Copyright © 2011-2022 走看看