[英]OPTIONS method with Java client returns 200/OK always
我有一个Jersey REST服务,当我从命令行使用curl
访问时,它会提供预期的结果:
$ curl -i -X OPTIONS http://localhost:7001/path/to/my/resource
HTTP/1.1 402 Payment Required
Date: Mon, 07 Aug 2017 01:03:24 GMT
...
$
由此,我得出我的REST服务已正确实现的信息。
但是,当我尝试从Java客户端调用它时,却得到200/OK
。
public class Main3 {
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:7001/path/to/my/resource");
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("OPTIONS");
int response = conn.getResponseCode();
System.out.println(response);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
我单步执行服务器代码,然后请求到达服务器中的Jersey代码,但此后,它以某种方式返回200/OK
而没有调用我的Resource。 我在这里做错了什么?
通过调试服务器,我知道在org.glassfish.jersey.server.ServerRuntime#process
方法中,选择的Endpoint
为org.glassfish.jersey.server.wadl.processor.OptionsMethodProcessor.GenericOptionsInflector
。 这总是返回200/OK
。 为什么没有选择用@OPTIONS
注释的资源方法呢?
事实证明,问题在于客户端代码未设置Acccept
标头,因此获得了默认的Accept:text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Accept:text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Accept:text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
。 curl
相反,将标题放在Accept:*/*
。 Jersey正在将curl
调用路由到我的资源,因为它接受了任何响应,但是我的资源没有@Produces(..)
批注(对于我的Java客户端代码接受的批注之一@Produces(..)
。
解决方法是添加以下行:
conn.setRequestProperty("Accept", "*/*");
在客户端代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.