[英]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.