有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java jersey http客户端自定义请求方法

使用以下代码,使用jersey

    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-apache-client4</artifactId>
    <version>1.13-b01</version>

我在使用自定义请求方法时遇到了一些问题,如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);

结果是出现以下异常:

 com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: Invalid HTTP method: FOOBAR

我尝试了各种方法试图解决这个问题,但没有成功

  • http://java.net/jira/browse/JERSEY-639已在上面的config.getProperties()行中实现。仍在接收错误
  • 当我切换到ApacheHTTP客户机时,从接收所有非GET和非PUT请求的服务器收到411个错误

长话短说,我想实现与via Java中类似的功能:

提前感谢您的反馈


共 (2) 个答案

  1. # 1 楼答案

    球衣2号。xClient,我们将设置属性

    true

    Client client = ClientBuilder.newClient();
    client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    String response = client.target(url).request().method("PATCH", entity, String.class);
    
  2. # 2 楼答案

    这不是一个bug,而是一个特性。:)

    但说真的。 HttpUrlConnection不允许您使用自定义HTTP方法,因为:

    // This restriction will prevent people from using this class to

    // experiment w/ new HTTP methods using java.

    因此,在Java6中,除了“GET”、“POST”、“HEAD”、“OPTIONS”、“PUT”、“DELETE”、“TRACE”之外,您不能使用其他方法

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