使用Jersey客户端进行PATCH请求

21

我想使用Jersey客户端执行一个由我们的服务器支持的PATCH请求进行测试。我的代码如下,但是我得到了com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: HTTP method PATCH doesn't support output异常。请问下面的代码有什么问题?

String complete_url = "http://localhost:8080/api/request";
String request = "[{\"op\":\"add\", \"path\":\"/name\", \"value\":\"Hello\"}]";
DefaultClientConfig config = new DefaultClientConfig();
    config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);
Client client = Client.create(config);
WebResource resource = client.resource(complete_url);
ClientResponse response = resource.header("Authorization", "Basic xyzabCDef")
 .type(new MediaType("application", "json-patch+json"))
 .method("PATCH", ClientResponse.class, request);

以下是完整的异常信息:

com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: HTTP method PATCH doesn't support output
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:155)
    at com.sun.jersey.api.client.Client.handle(Client.java:652)
    at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682)
    at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
    at com.sun.jersey.api.client.WebResource$Builder.method(WebResource.java:634)
    at com.acceptance.common.PatchTest.patch(PatchTest.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.net.ProtocolException: HTTP method PATCH doesn't support output
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1021)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler$1$1.getOutputStream(URLConnectionClientHandler.java:238)
    at com.sun.jersey.api.client.CommittingOutputStream.commitStream(CommittingOutputStream.java:117)
    at com.sun.jersey.api.client.CommittingOutputStream.write(CommittingOutputStream.java:89)
    at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
    at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:272)
    at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:276)
    at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:122)
    at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:212)
    at java.io.BufferedWriter.flush(BufferedWriter.java:236)
    at com.sun.jersey.core.util.ReaderWriter.writeToAsString(ReaderWriter.java:191)
    at com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider.writeToAsString(AbstractMessageReaderWriterProvider.java:128)
    at com.sun.jersey.core.impl.provider.entity.StringProvider.writeTo(StringProvider.java:88)
    at com.sun.jersey.core.impl.provider.entity.StringProvider.writeTo(StringProvider.java:58)
    at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:300)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:217)
    at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:153)

有没有什么方法可以抑制这些警告或完全避免它们?- https://stackoverflow.com/a/67682124/16022919 - njkmohan
4个回答

57

提醒 - 如果有人在 Jersey 2 中遇到此问题,请查看 HttpUrlConnectorProvider 文档

并按以下方式设置 SET_METHOD_WORKAROUND 属性:

Client jerseyClient = ClientBuilder.newClient()
        .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true)
        ... etc ...

我花了很长时间才找到这个 - 我想我可以帮助缩短其他人的学习曲线。


3
它起作用了 ;) 无论如何,自2010年(rfc 5789)以来,PATCH已成为HTTP标准的一部分...很奇怪的是,在2017年,Jersey仍然不支持它的本地化。 - arcuri82
它解决了错误,但我正在使用一个正常工作的客户端进行未授权的401调用,需要授权的get调用也是如此,你有什么想法? - Roesmi

15

如果您正在使用HttpsUrlConnection(请注意's'),那么设置HttpUrlConnectorProvider.SET_METHOD_WORKAROUND将不起作用。继续阅读以获取详细解决方案。

在我的情况下,设置HttpUrlConnectorProvider.SET_METHOD_WORKAROUND属性会导致NoSuchFieldException,因为我的HttpUrlConnection实例实际上是sun.net.www.protocol.https.HttpsURLConnectionImpl类型,而它的超类是javax.net.ssl.HttpsURLConnection(它继承自HttpUrlConnection)。

所以当Jackson代码尝试从我的连接实例中的超类(javax.net.ssl.HttpsURLConnection的实例)获取方法字段时:

/**
 * Workaround for a bug in {@code HttpURLConnection.setRequestMethod(String)}
 * The implementation of Sun/Oracle is throwing a {@code ProtocolException}
 * when the method is other than the HTTP/1.1 default methods. So to use {@code PROPFIND}
 * and others, we must apply this workaround.
 *
 * See issue http://java.net/jira/browse/JERSEY-639
 */
private static void setRequestMethodViaJreBugWorkaround(final HttpURLConnection httpURLConnection, final String method) {
    try {
        httpURLConnection.setRequestMethod(method); // Check whether we are running on a buggy JRE
    } catch (final ProtocolException pe) {
        try {
            final Class<?> httpURLConnectionClass = httpURLConnection.getClass();
            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws NoSuchFieldException, IllegalAccessException {
                    final Field methodField = httpURLConnectionClass.getSuperclass().getDeclaredField("method");
                    methodField.setAccessible(true);
                    methodField.set(httpURLConnection, method);
                    return null;
                }
            });
        } catch (final PrivilegedActionException e) {
            final Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }
    }
}

我们收到一个 NoSuchFieldException 异常,它说明不存在名为 method 的字段(因为 getDeclaredFields() 会获取所有字段,不考虑它们的可访问性,但只会获取当前类的字段,而不会获取当前类可能继承的任何基类的字段)。

因此,我研究了Java的 HttpUrlConnection 代码,并发现允许的方法是由一个私有静态 String[] 指定的:

 /* Adding PATCH to the valid HTTP methods */
 private static final String[] methods = {
     "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"
 };
解决方案是使用反射更改这个方法数组:

使用反射更改此方法数组即可解决问题。

 try {
         Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
         methodsField.setAccessible(true);
         // get the methods field modifiers
         Field modifiersField = Field.class.getDeclaredField("modifiers");
         // bypass the "private" modifier 
         modifiersField.setAccessible(true);

         // remove the "final" modifier
         modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

         /* valid HTTP methods */
         String[] methods = {
                    "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH"
         };
         // set the new methods - including patch
         methodsField.set(null, methods);

     } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
      e.printStackTrace();
     }

由于方法字段是静态的,改变它的值适用于扩展 HttpUrlConnection 的任何具体实例,包括 HttpsUrlConnection

顺便说一下:我希望Java将PATCH方法添加到JDK中,或者从Jackson开始通过他们的解决方法在整个层次结构中执行字段查找。

无论如何,我希望这个解决方案能为您节省一些时间。


2
非常感谢您发布这个!我可能需要几年才能弄明白,而我告诉了一位同事,我可以实现这个功能,因为我看到其他人这样做了,但没有意识到中间有一个不同的类会让我搞砸一切! - Karl Henselin
2
谢谢您提供的使用Java反射的解决方案,它对我很有帮助。 - Developer
1
非常高级的答案! - Fabrizio Stellato

12

这是当前JDK实现中的一个错误,在JDK8的实现中已经修复。请查看此链接以获取详细信息 https://bugs.openjdk.java.net/browse/JDK-7157360

有一种方法可以规避此问题,但Jersey团队决定不进行修复 https://github.com/eclipse-ee4j/jersey/issues/1639

我能想到的两个解决方案:

  1. 使用支持HttpPatch方法的Apache Http Client
  2. 使用Jersey Client PostReplaceFilter,但必须修改容器代码并在发出POST请求时包括X-HTTP-Method-Override标头,值为PATCH。请参阅http://zcox.wordpress.com/2009/06/17/override-the-http-request-method-in-jersey/

我迁移到了Jersey 2.1(2.35),在客户端创建时添加此属性可以正常工作:jerseyClient.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); 调用代码如下:Response response = invocationBuilder.method("PATCH", Entity.entity(jsonRequestString, MediaType.APPLICATION_JSON_TYPE)); - Kandy

3

简单明了的答案是:

依赖项

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client -->
 <dependency>
     <groupId>org.glassfish.jersey.core</groupId>
     <artifactId>jersey-client</artifactId>
     <version>2.27</version>
 </dependency>

需要添加 HttpUrlConnectorProvider.SET_METHOD_WORKAROUND=true
Client client = ClientBuilder.newClient(clientConfig).property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);

请求

client.target("base_url").path("end_point").request().headers("your_headers")
       .build("PATCH", Entity.entity("body_you_want_to_pass", "content-type"))
       .invoke();

嗯,那给了我一个“不支持的方法”错误。但是同样的“PATCH”方法在 JavaScript 客户端中可以工作。 - Gana
你是否使用了和我提到的相同依赖? - NarendraR
是的,我使用了相同版本的上述依赖项。 - Gana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接