Retrofit & HTTP Patch

限于喜欢 提交于 2019-12-11 01:39:18

问题


So I want to make a PATCH request using Retrofit but currently I cannot add okhttp to my classpath. When I attempt to make a PATCH request I get the stack trace below. Is there any other way I could use Patch without using okhttp?

    java.net.ProtocolException
        at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:644)
        at retrofit.client.UrlConnectionClient.prepareRequest(UrlConnectionClient.java:50)
        at retrofit.client.UrlConnectionClient.execute(UrlConnectionClient.java:37)
        at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:358)
        at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:264)
        at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:315)
        at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
        at retrofit.Platform$Android$2$1.run(Platform.java:142)
        at java.lang.Thread.run(Thread.java:1019)
06-09 10:53:09.349    1809-1897/**.****.****** D/Retrofit﹕ ---- END ERROR

回答1:


This is a limitation of HttpUrlConnection. You can either use Apache or OkHttp which both support PATCH as an alternative client. This can be done explicitly in the builder:

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(..)
    .setClient(new OkClient())
    .build()

Additionally, some servers allow specifying an X-HTTP-Method-Override header for changing the method. With this you would send a POST but include PATCH as this header value. Again, this requires server support.

Finally, one other option would be to subclass Retrofit's UrlConnectionClient and use reflection to change the field which holds the HTTP method. This is very fragile, prone to future breakage, and is the worst option in my opinion.



来源:https://stackoverflow.com/questions/24118929/retrofit-http-patch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!