当前位置 : 主页 > 编程语言 > java >

SpringBoot 如何使用RestTemplate来调用接口

来源:互联网 收集:自由互联 发布时间:2021-11-19
目录 使用RestTemplate来调用接口 1.新建一个配置类,配置RestTemplate的Bean 2.多种传输和接收参数的方式 2.1postForObject方法 postForEntity 2.2getForObject方法 2.3getForEntity方法 RestTemplate调用接口总结
目录
  • 使用RestTemplate来调用接口
    • 1.新建一个配置类,配置RestTemplate的Bean
    • 2.多种传输和接收参数的方式
      • 2.1postForObject方法
    • postForEntity
      • 2.2getForObject方法
      • 2.3getForEntity方法
  • RestTemplate调用接口总结
    • 1.这是接口信息
      • 2.接口

      使用RestTemplate来调用接口

      1.新建一个配置类,配置RestTemplate的Bean

      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.http.client.ClientHttpRequestFactory;
      import org.springframework.http.client.SimpleClientHttpRequestFactory;
      import org.springframework.web.client.RestTemplate;
       
      /**
       * RestTemplate配置模板
       *
       * @author like
       */
      @Configuration
      public class RestTemplateConfig {
       
          @Bean
          public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
              return new RestTemplate(factory);
          }
       
          @Bean
          public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
              SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
              factory.setReadTimeout(5000);//单位为ms
              factory.setConnectTimeout(5000);//单位为ms
              return factory;
          } 
      }

      注意点:如果在编译器中提示factory不能自动注入,那应该时跟其他类有冲突,有多个 ClientHttpRequestFactory

      把这个factory的名字改一下,改成其他的就好了,比如这里就直接改成 simpleClientHttpRequestFactory

      2.多种传输和接收参数的方式

      2.1postForObject方法

      postForObject指post请求,并返回一个Object对象。

      • 第1个参数:请求的url地址
      • 第2个参数:其实是HttpEntity,这个类主要有三种构造方法,如下

      new HttpEntity(请求体)

      new HttpEntity(请求头)

      new HttpEntity(请求体,请求头)

      • 第3个参数:返回的结果类型,这里String.class表示返回结果是一个字符串。
      • 第4个参数:参数值,这里有Map和 可变参数两种形式(通常用不到,数据通常放在Json里就全部传输过去了)

      2.1.1使用Json来传递和接收数据

      首先引入fastJson的pom配置

      <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
      		<dependency>
      			<groupId>com.alibaba</groupId>
      			<artifactId>fastjson</artifactId>
      			<version>1.2.49</version>
      		</dependency>

      在实现类中注入RestTemplate

      接下来new一个 ExpressionDomain 对象,将这个对象转化成JSONObject。使用Json来传递数据

      public void postByDefault()
      {
          ExpressionDomain expressionDomain=new ExpressionDomain("hello","hasaki","win");
          JSONObject jsonObj = (JSONObject) JSONObject.toJSON(expressionDomain);
          
          //设置请求头
          HttpHeaders headers = new HttpHeaders();
          headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
          headers.add("Accept", MediaType.APPLICATION_JSON.toString());
       
          //请求体
          HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
          
          //发起请求
          String jsonResult = restTemplate.postForObject("http://localhost:8081/findDataByReflection" , formEntity, String.class);
          
          //将Json字符串解析成对象
          Response resp = JSON.parseObject(jsonResult, new TypeReference<Response>() {});
      }

      接收端

      @RequestBody注解一个参数,用于自动解析Json为对象。返回的Response也是一个对象,添加@ResponseBody注解,将返回Json字符串。解析的时候将Json字符串解析成对象即可。

      postForEntity

      和getForEntity原理是一样的,下面会讲到。

      2.2getForObject方法

      getForObject指get请求,并返回一个Object对象。这里有3种方法。

      • 第1个参数:请求的url地址
      • 第2个参数:返回的结果类型,这里String.class表示返回结果是一个字符串。
      • 第3个参数:参数值,这里有Map和 可变参数两种形式

      2.2.1 通过Map传参数的方式

      可以使用map来封装请求参数,并作为getForObject的第三个参数,同时修改url如下,map中的"1"会替换url中的{1},"2"会替换url中的{2}

      Map map = new HashMap();
      map.put("1", "hello");
      map.put("2", "world");
      String result = restTemplate.getForObject("http://localhost:8081/getIds?param1={1}&param2={2}", String.class,map);

      接口端:

      @RequestMapping(value = "/getIds", method = RequestMethod.GET)
      public @ResponseBody String getIds(String param1, String param2) {
          return param1 + param2;
      }

      2.2.2 通过可变参数的方式

      也可以直接将要传递的值放到getForObject方法的参数结尾,数量不限,它会按顺序替换{1}和{2}。接口端代码还是和2.2.1的一样

      String result = restTemplate.getForObject("http://localhost:8081/getIds?param1={1}&param2={2}", String.class, "hello", "world");

      2.3getForEntity方法

      getForEntity和getForObject的用法是一样的,只是其返回结果是一个ResponseEntity,其中包含了更多的响应信息,比如:

      		ResponseEntity response = restTemplate.getForEntity("http://localhost:8081/getIds",String.class);
      		response.getHeaders();		//响应头
      		response.getStatusCode();	//响应码
      		response.getBody();			//响应体,即前面的result

      RestTemplate调用接口总结

      1.这是接口信息

          @PostMapping("/testm")
          public ReturnResult show11(@RequestParam("id") String id,
                                     @RequestParam("name") String name) {
              System.out.println(id);
              UserInfo userInfo = userInfoMapper.selectByUserName(name); 
              return ReturnResult.create(userInfo);
          }

      这是restTemplate调用

          //Post,@RequestParam---postForEntity
          @Test
          public void sho11() {
              String url = "http://127.0.0.1:8099/user/testm";
              MultiValueMap<String, String> request = new LinkedMultiValueMap<>();
              request.add("id", "12324");
              request.add("name", "nanc");
       
              ResponseEntity<ReturnResult> resp = restTemplate.postForEntity(url, request, ReturnResult.class);
              ReturnResult body = resp.getBody();
              UserInfo data = body.getData();
              System.err.println(data.getUserId());
              System.out.println(data);  
          }

      2.接口

          @GetMapping("/testp")
          public ReturnResult show22(@RequestParam String name,
                                     @RequestParam Integer age,
                                     @RequestParam String clazz) {
              System.out.println(name + "-" + age + "-" + clazz);
              UserInfo userInfo = userInfoMapper.selectByUserName(name);
              return ReturnResult.create(userInfo);
          }

      resttemplate

          //Get ,@RequestParam-----getForObject
          @Test
          public void sho12() {
              String url = "http://127.0.0.1:8099/rest/testp?name={name}&age={age}&clazz={clazz}";
              Map<String, Object> map = new HashMap<>();
              map.put("name", "nanc");
              map.put("age", 34);
              map.put("clazz", "12");
              ReturnResult forObject = restTemplate.getForObject(url, ReturnResult.class, map);
              UserInfo data = forObject.getData();
              System.out.println(data);
          }
       

      以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。

      上一篇:springboot restTemplate连接池整合方式
      下一篇:没有了
      网友评论