简体   繁体   中英

OPTIONS method with Java client returns 200/OK always

I have a Jersey REST service, which when I access using curl from the command line gives me the expected result:

$ 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
...
$

From this, I gather that my REST service is implemented correctly.

But when I try to invoke this from a Java client, I get a 200/OK instead.

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

I stepped through the server code and the request is reaching the Jersey code in the server, but after that, it somehow returns 200/OK without calling my Resource. What am I doing wrong here?

From debugging the server, I know that in the org.glassfish.jersey.server.ServerRuntime#process method, the Endpoint chosen is org.glassfish.jersey.server.wadl.processor.OptionsMethodProcessor.GenericOptionsInflector . This always returns 200/OK . Why is my resource's method annotated with @OPTIONS not chosen instead?

It turned out that the problem was that the client code does not set an Acccept header, and so get a default of 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 instead put the header Accept:*/* . Jersey was routing the curl call to my resource because of it accepts any response, but my resource did not have the @Produces(..) annotation for one of those accepted by my Java client code.

The fix was to add the line:

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

in the client code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM