调用第三方接口的方式(简洁版)

记录主要是为了方便使用,可能不够透彻,但是基本能直接使用

可直接使用hutool的HttpUtil封装的jar包

例如:

使用get请求

String url ="https://www.baidu.com";

 HttpUtil.get(url);

使用get方法时可按照自己的需求进行配置,比如设置超时时间,放入map,放入body等等

可直接塞入get后面的括号中;                     

使用post方法

HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("city", "北京");

String result= HttpUtil.post("https://www.baidu.com", paramMap);

使用RestTemplate简单粗暴 :

使用restTemplate防伪标restful接口非常的简单,下面先放个简单的例子:

//请求地址

String url = "http://localhost:8080/testHelloWorld";

//入参

Map map=new HashMap();

map("hello",aa);

RestTemplate restTemplate=new RestTemplate

ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(url,map, String.class)

其中restTemplate 中传入的三个参数分别为请求地址,请求参数和HTTP响应转换被转换成的对象类型,并且根据postForEntity这使用的方法不同,返回类型可变化

POST请求

调用POSTForObject方法、使用postForEntity方法、使用exchange方法

postForObject和postForEntity方法的区别主要在于可以在postForEntity方法中设置header的属性,当需要指定header的属性值的时候,使用postForEntity方法。exchange方法和postForEntity类似,但是更灵活,exchange还可以调用get请求。

private static void createTest(){
    final String uri = "http://localhost:8080/test";
    TestVO newEmployee = new TestVO(-1, "aa", "ming", "[email protected]");
    RestTemplate restTemplate = new RestTemplate();
    TestVO result = restTemplate.postForObject( uri, newTest, TestVO.class);
 
    System.out.println(result);
}

get请求

private static void getTest(){
    final String uri = "http://localhost:8080/test";
     
    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);
     
    System.out.println(result);
}

RestTemplate配置类

@Configuration//加上这个注解作用,可以被Spring扫描
public class RestTemplateConfig implements WebMvcConfigurer {
    /**
     * 创建RestTemplate对象,将RestTemplate对象的生命周期的管理交给Spring
     */
    @Bean
    public RestTemplate restTemplate(){
        // RestTemplate restTemplate = new RestTemplate();
        //设置中文乱码问题方式一
        // restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(Charset.forName("UTF-8")));
        // 设置中文乱码问题方式二
        // restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 支持中文编码
        return new RestTemplate();
    }

}

猜你喜欢

转载自blog.csdn.net/xtldcn/article/details/129381447
今日推荐