2017-08-07 136 views
0

我有一個新澤西州的REST服務,當我訪問使用curl命令行,給了我預期的結果:OPTIONS方法與Java客戶端返回200/OK總是

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

我通過服務器代碼加強和請求到達服務器澤西代碼,但在那之後,它在某種程度上返回200/OK不叫我的資源。我在這裏做錯了什麼?

從調試服務器,我知道在org.glassfish.jersey.server.ServerRuntime#process方法中,所選的Endpointorg.glassfish.jersey.server.wadl.processor.OptionsMethodProcessor.GenericOptionsInflector。這總是返回200/OK。爲什麼我的資源的方法用@OPTIONS註釋而不選擇?

回答

0

原來問題是客戶端代碼沒有設置Acccept標題,因此得到的默認值爲Accept:text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2curl改爲將標題Accept:*/*。 Jersey正在將curl調用路由到我的資源,因爲它接受任何響應,但是我的資源沒有爲我的Java客戶端代碼接受的那些註冊之一登錄@Produces(..)

此修復程序是添加一行:

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

在客戶端的代碼。