Java 客户端 returns 的 OPTIONS 方法总是 200/OK

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 代码,但在那之后,它以某种方式 returns 200/OK 没有调用我的资源。我在这里做错了什么?

通过调试服务器,我知道在org.glassfish.jersey.server.ServerRuntime#process方法中,选择的Endpointorg.glassfish.jersey.server.wadl.processor.OptionsMethodProcessor.GenericOptionsInflector。这总是 returns 200/OK。为什么我的资源方法没有选择 @OPTIONS 注释?

原来问题是客户端代码没有设置 Acccept header,所以得到默认值 Accept:text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2curl 而不是 header Accept:*/*。 Jersey 将 curl 调用路由到我的资源,因为它接受任何响应,但我的资源没有 Java 客户端代码接受的其中一个注释的 @Produces(..) 注释。

修复方法是添加以下行:

conn.setRequestProperty("Accept", "*/*");

在客户端代码中。