假设您的实现包含这样的自定义注释
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.HttpMethod;
@HttpMethod("PATCH")
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PATCH {}
试图用Client
String response = target.request().method("PATCH", Entity.text("Hello"), String.class);
默认情况下不支持,并且会出现异常
java.net.ProtocolException: Invalid HTTP method: PATCH
这不是Client
API 的直接问题,而是较低级别的 Java API 的问题。似乎是一些安全限制。
使用客户端 API,我们可以通过设置属性来覆盖它
在 中JerseyTest
,配置 的一种方法Client
是覆盖configureClient
,并使用 设置属性ClientConfig
。您可以轻松地在Client
自身上设置属性,但要保持JerseyTest
框架的精神(我们不需要显式访问Client
,下面的示例将只是覆盖该方法
public class PatchTest extends JerseyTest {
@Path("patch")
public static class PatchResource {
@PATCH
@Produces(MediaType.TEXT_PLAIN)
public String getPatch(String request) {
return "Patched " + request;
}
}
@Override
protected void configureClient(final ClientConfig config) {
config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
}
@Override
public Application configure() {
return new ResourceConfig(PatchResource.class);
}
@Test
public void doPatchTest() {
WebTarget target = target("patch");
String response = target.request().method("PATCH", Entity.text("Hello"), String.class);
Assert.assertEquals("Patched Hello", response);
System.out.println(response);
}
}