簡體   English   中英

使用 Jersey 客戶端的 PATCH 請求

[英]PATCH request using Jersey Client

我想執行我們的服務器支持的 PATCH 請求,以便使用 Jersey 客戶端進行測試。 我的代碼如下,但我得到com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: HTTP method PATCH doesn't support output exception。 有人可以讓我知道下面的代碼有什么問題嗎?

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)

僅供參考 - 以防萬一有人在 Jersey 2 中遇到此問題,請參閱HttpUrlConnectorProvider 文檔

並使用 SET_METHOD_WORKAROUND 屬性如下:

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

我花了很長時間才找到這個 - 認為我可以幫助縮短其他人的學習曲線。

如果您使用的是HttpsUrlConnection (注意's' ) - 那么設置HttpUrlConnectorProvider.SET_METHOD_WORKAROUND將不起作用。 繼續閱讀以獲取詳細的解決方案。

就我而言,設置HttpUrlConnectorProvider.SET_METHOD_WORKAROUND屬性會導致NoSuchFieldException因為我的HttpUrlConnection實例實際上是類型: sun.net.www.protocol.https.HttpsURLConnectionImpl並且它是超級: javax.net.ssl.HttpsURLConnection (從HttpUrlConnection繼承)。

因此,當 Jackson 代碼嘗試從我的連接實例 super( 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();
     }

由於 methods 字段是靜態的,因此更改其值適用於擴展HttpUrlConnection任何具體實例,包括HttpsUrlConnection

旁注:我更喜歡 Java 將 PATCH 方法添加到 JDK 或從 Jackson 添加到他們的解決方法中的整個層次結構中執行字段查找。

無論如何,我希望這個解決方案可以為您節省一些時間。

這是當前 JDK 實現中的一個錯誤,已在 JDK8 實現中修復。查看此鏈接了解詳細信息https://bugs.openjdk.java.net/browse/JDK-7157360 有一種方法可以解決這個問題,但 Jersey 團隊決定不修復它https://github.com/eclipse-ee4j/jersey/issues/1639

我能想到的2個解決方案

  1. 使用支持 HttpPatch 方法的 Apache Http Client
  2. 使用 Jersey 客戶端 PostReplaceFilter 但必須修改容器代碼,並在發出發布請求時包含 X-HTTP-Method-Override 標頭,其值為 PATCH。 參考http://zcox.wordpress.com/2009/06/17/override-the-http-request-method-in-jersey/ ]

簡單的答案是:

依賴關系

<!-- 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM