2013-12-20 68 views
2

我正在用澤西島Java庫編寫客戶端應用程序,我不會成功地向服務器發送cookie。我的錯誤在哪裏?這裏是我的代碼:澤西島 - 在客戶端上設置的cookie不會到達服務器

客戶:

Client client = ClientBuilder.newClient(); 

    WebTarget webTarget = client.target(getUrl()); 

    //Create invocation builder 
    Invocation.Builder invocationBuilder = webTarget.request(getMime_type()); 

    //Set the cooky 

    invocationBuilder = invocationBuilder.cookie("mioCookie","value of my cookie"); 

    Response response = invocationBuilder.get(); 

SERVER:

@Path("/file") 
public class FileService { 
    Logger LOG=Logger.getLogger(this.getClass().getName()); 
    private static final String FILE_PATH = "file.log"; 

    @GET 
    @Path("/get") 
    @Produces("text/plain") 
    public Response getFile(@CookieParam(value = "mioCookie") String mioCookie) { 
     LOG.info("***** Cookie in input: " + mioCookie); 
     File file = new File(FILE_PATH); 
     NewCookie modifiedCookie = new NewCookie("mioCookie", mioCookie + "- modified"); 
     ResponseBuilder response = Response.ok((Object) file); 
     response.header("Content-Disposition", "attachment; filename=\"file_from_server.log\""); 
     response.cookie(modifiedCookie); 
     return response.build(); 

    } 

什麼是日誌寫的是:

infos: ***** Cookie in input: null. 

我在哪裏錯了?

+1

您是否嘗試使com.sun.jersey.spi.container.ContainerRequestFilters過濾器登錄傳入的請求?感謝這一點,您將知道問題出在客戶端還是服務器代碼中。 –

+0

@Adam這是一個很好的建議,這也可以使用網絡調試工具來檢測互聯網流量(例如http://fiddler2.com/) – LeastOne

+0

剛剛用Jersey 2.5(客戶端)和Jersey 1.17(服務器)測試了您的代碼。它的工作原理:'*****輸入Cookie:我的cookie的值 –

回答

1

在撥打電話時,您可以簡單地添加Response response = target.request().cookie(Your Cookie)。不要明確調用構建器,因爲它不會在最終調用中添加該cookie。這應該會將Cookie添加到您的通話中。 一個例子呼籲後加入更加清晰 Response response =webTarget.request().accept(MediaType.APPLICATION_JSON).cookie(cookie).buildPost(Entity.entity(jsonObject.toString(), MediaType.APPLICATION_JSON)).invoke(); 希望幫助