SpringBoot之AsyncRestTemplate Patch请求无效

使用AsyncRestTemplate exchange()方式,method为patch时报错:

java.net.ProtocolException: Invalid HTTP method: PATCH

经过一番调试,还是无法解决该问题,最后使用RestTemplate ,只是无法异步了。

延伸:

HttpURLConnection conn = (HttpURLConnection) new URL("http://example.com").openConnection();

如果是使用该方法,远程调用API

解决方案:

conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestMethod("POST");

另外springboot使用AsyncRestTemplate时,是无法自动@Autowired,需要在@Configuration 类中

@Bean
public AsyncRestTemplate asyncRestTemplate()
{
    return new AsyncRestTemplate();
}

使用方法

//调用完后立即返回(没有阻塞)
        ListenableFuture<ResponseEntity<String>> forEntity = template.getForEntity(url, String.class);
        //异步调用后的回调函数
        forEntity.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
            //调用失败
            @Override
            public void onFailure(Throwable ex) {
                logger.error("=====rest response faliure======");
            }
            //调用成功
            @Override
            public void onSuccess(ResponseEntity<String> result) {
                logger.info("--->async rest response success----, result = "+result.getBody());
            }
        });

总之,AsyncRestTemplate挺不好用的,能不用就不用吧,看了官方文档,都已经弃用了,改用 WebClient

posted @ 2019-03-13 19:01  TroubleBoy丶  阅读(432)  评论(0编辑  收藏  举报