泽西岛 - 客户端上设置的cookie不会到达服务器

时间:2013-12-20 16:10:39

标签: java cookies jersey

我正在编写一个带有jersey java库的客户端应用程序,我没有成功将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 个答案:

答案 0 :(得分: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(); 希望有所帮助