使用RestTemplate跨接口调用时出现异常问题

1.patch请求异常

想了解patch请求可以点击这里
在这里插入图片描述

// 本来我是使用post请求的,结果写代码的时候误写了patch请求,结果出现了异常
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(...);  // post是没问题的

// 
RestTemplate restTemplate = new RestTemplate();
restTemplate.patchForObject(...);  // patch请求出现了问题

2.解决办法

// 使用了HttpComponentsClientHttpRequestFactory 
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);

3. 原因

1.查看源码我发现,RestTemplate的请求默认是由ClientHttpRequestFactory 进行创建的

private ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

在这里插入图片描述
2.然后进入ClientHttpRequestFactory类,去查看是怎么创建的,这里可以看到创建请求的方法中调用了HttpURLConnection类进行连接。

public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
        HttpURLConnection connection = this.openConnection(uri.toURL(), this.proxy);
        this.prepareConnection(connection, httpMethod.name());
        return (ClientHttpRequest)(this.bufferRequestBody ? new SimpleBufferingClientHttpRequest(connection, this.outputStreaming) : new SimpleStreamingClientHttpRequest(connection, this.chunkSize, this.outputStreaming));
    }

3.因此我又进入了HttpURLConnection类,发现这个连接不支持patch请求

// 在package java.net;包下面

/* valid HTTP methods */
    private static final String[] methods = {
        "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"
    };

4.查看HttpComponentsClientHttpRequestFactory类源码我们可以发现它是支持patch请求的

// 在org.springframework.http.client;包下

protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
        switch(httpMethod) {
        case GET:
            return new HttpGet(uri);
        case HEAD:
            return new HttpHead(uri);
        case POST:
            return new HttpPost(uri);
        case PUT:
            return new HttpPut(uri);
        case PATCH:
            return new HttpPatch(uri);
        case DELETE:
            return new HttpComponentsClientHttpRequestFactory.HttpDelete(uri);
        case OPTIONS:
            return new HttpOptions(uri);
        case TRACE:
            return new HttpTrace(uri);
        default:
            throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Listen·Rain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值