Spring Boot OpenFeign PATCH 请求报错:java.net.ProtocolException: Invalid HTTP method: PATCH

Spring Boot OpenFeign About 2,604 words

错误信息

java.net.ProtocolException: Invalid HTTP method: PATCH
    at java.base/java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:489)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(HttpURLConnection.java:598)
    at feign.Client$Default.convertAndSend(Client.java:163)
    at feign.Client$Default.execute(Client.java:103)
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:119)
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:89)
    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:100)
    at jdk.proxy2/jdk.proxy2.$Proxy136.routePatch(Unknown Source)

原因

OpenFeign默认使用的是Java提供的HttpURLConnection,而HttpURLConnection不支持PATCH请求。

解决方法

方法一

添加feign-httpclient依赖,使用HttpClient代替HttpURLConnection

<dependency>
    <!-- Required to use PATCH -->
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>${feign.version}</version>
</dependency>

注意:OpenFeign的版本与feign-httpclient的版本需查看发布时间,否则会抛出异常:

APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.cloud.openfeign.annotation.QueryMapParameterProcessor.processArgument(QueryMapParameterProcessor.java:48)

The following method did not exist:

    'feign.MethodMetadata feign.MethodMetadata.queryMapEncoded(boolean)'

The method's class, feign.MethodMetadata, is available from the following locations:

    jar:file:/app/app.jar!/BOOT-INF/lib/feign-core-12.1.jar!/feign/MethodMetadata.class

The class hierarchy was loaded from the following locations:

    feign.MethodMetadata: jar:file:/app/app.jar!/BOOT-INF/lib/feign-core-12.1.jar!/


Action:

Correct the classpath of your application so that it contains a single, compatible version of feign.MethodMetadata

方法二

仍然使用HttpURLConnection,请求设置为POST,但添加X-HTTP-Method-Override请求头覆盖POST请求。

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

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

Maven 仓库

https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign

https://mvnrepository.com/artifact/io.github.openfeign/feign-httpclient

相关 issue

https://github.com/spring-cloud/spring-cloud-openfeign/issues/366

https://stackoverflow.com/questions/25163131/httpurlconnection-invalid-http-method-patch/32503192#32503192

Views: 1,624 · Posted: 2023-02-17

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh