[英]jersey http client custom request method
With the following code, using jersey
: 使用以下代码,使用
jersey
:
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client4</artifactId>
<version>1.13-b01</version>
I have issues using custom request methods, like FOOBAR, PATCH, SEARCH, etc. Those which do not exist in httpUrlConnection
. 我有使用自定义请求方法的问题,如FOOBAR,PATCH,SEARCH等。在
httpUrlConnection
不存在。
DefaultClientConfig config = new DefaultClientConfig();
config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);
Client c = Client.create(config);
Form f = new Form();
f.add("id", "foobar");
WebResource r = c.resource("http://127.0.0.1/foo");
String methodName = "foobar";
String response = r.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("USER-AGENT", "my-java-sdk /1.1").method(methodName.toUpperCase(), String.class, f);
The result is the following exception: 结果是以下异常:
com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: Invalid HTTP method: FOOBAR
I have tried various ways to try and resolve this, without success. 我已经尝试了各种方法来尝试解决这个问题,但没有成功。
config.getProperties()
line. config.getProperties()
行中实现了。 Still receiving the error Long story short, I want to implement similar functionality as is available in via Java: 长话短说,我想实现类似于via Java中提供的功能:
Thank you in advance for your feedback 提前感谢您的反馈
With Jersey 2.x Client
, we would set the property 使用Jersey 2.x
Client
,我们将设置该属性
to true
为
true
Client client = ClientBuilder.newClient();
client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
String response = client.target(url).request().method("PATCH", entity, String.class);
It is not a bug, it is a feature. 它不是一个bug,它是一个功能。 :)
:)
but seriously. 不过实话说。 HttpUrlConnection do not allow you use custom HTTP methods because:
HttpUrlConnection不允许您使用自定义HTTP方法,因为:
// This restriction will prevent people from using this class to
//此限制将阻止人们使用此类
// experiment w/ new HTTP methods using java.
//使用java实验w / new HTTP方法。
So you cannot use other methods than (in java 6): "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE" 所以你不能使用其他方法(在java 6中):“GET”,“POST”,“HEAD”,“OPTIONS”,“PUT”,“DELETE”,“TRACE”
Jersey provides a workaround and it uses reflection to omit this checking: Jersey提供了一种解决方法,它使用反射来省略此检查:
DefaultClientConfig config = new DefaultClientConfig();
config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION
_SET_METHOD_WORKAROUND, true);
Client c = Client.create(config);
WebResource r = c.resource("http://google.com");
String reponse = r.method("FOOBAR", String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.