RestTemplate 工具类

RestTemplate 工具类

  • pom
  • 创建RestTemplate组件
  • 发送请求测试

pom

 <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <spring.version>5.3.6spring.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.11version>
        dependency>






        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.1version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.22version>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.25version>
        dependency>
    dependencies>

创建RestTemplate组件

@Configuration
public class BeanConfig {
     

    @Bean
    public RestTemplate restTemplate() {
     
        return new RestTemplate();
    }
}

RestTemplate 工具类_第1张图片

发送请求测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = BeanConfig.class)
public class RestTemplateTest {
     
    public static final Logger log = LoggerFactory.getLogger(RestTemplateTest.class);

    @Autowired
    private RestTemplate restTemplate;

   @Test
   public void testRestTemplate() {
     
       // 1、设置请求头
       HttpHeaders headers = new HttpHeaders();
       headers.setContentType(MediaType.APPLICATION_JSON);
       // 2、设置请求体
       Map params = new HashMap();
       params.put("customData", "123456");
       params.put("priority", "0");
       params.put("agentNo", "");
       params.put("direction", "1");
       HttpEntity httpEntity = new HttpEntity<>(params, headers);
       // 发送post请求
       JSONObject jsonObject = restTemplate.postForObject("http://172.16.1.134:8113/mi/addTask", httpEntity, JSONObject.class);
       System.out.println(jsonObject);

       String code = jsonObject.getString("code");
       if(code!=null){
     
           if("0".equals(code)){
     
               Map map = new HashMap();
               map.put("data", jsonObject.get("data"));
               System.out.println(jsonObject.get("data"));
           }
       }
   }
}

你可能感兴趣的:(#,常用工具类utils,java,spring,restful)