繁体   English   中英

从Java客户端应用程序的请求中检索从CookieStore中设置的cookie

[英]Retrieve cookies from CookieStore set in request from java client application

我有一个Java客户端,该客户端创建一个请求并在调用其余服务之前在CookieStore中设置cookie。

我正在尝试以这种方式在客户端和localContext上设置它(无论哪个起作用)

BasicClientCookie cookie = new BasicClientCookie("RSOMyLogin", "NDQ0NDQ0NDQ0");
cookie.setDomain("localhost");
cookie.setPath("/uploadFiles");
cookieStore.addCookie(cookie);
HttpPost httpRequest = new HttpPost(boxUploadURL);
CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute("RSOMyLogin", cookieStore);
HttpResponse httpResponse = client.execute(httpRequest, localContext);
System.out.println("response  = "+httpResponse.toString());

它可以在控制台上正常打印,但没有Cookie

response  = HttpResponseProxy{HTTP/1.1 500  [Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, Access-Control-Allow-Credentials: true, Access-Control-Allow-Headers: authorization, content-type, x-auth-token, Cache-Control, remember-me, WWW-Authenticate, loggedinuser, Access-Control-Expose-Headers: xsrf-token, fileName, Content-Disposition, Content-Length, Content-Type, X-Content-Type-Options: nosniff, X-XSS-Protection: 1; mode=block, Cache-Control: no-cache, no-store, max-age=0, must-revalidate, Pragma: no-cache, Expires: 0, X-Frame-Options: DENY, X-Application-Context: application:local:9191, Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Tue, 27 Aug 2019 14:31:10 GMT, Connection: close] ResponseEntityProxy{[Content-Type: application/json;charset=UTF-8,Chunked: true]}}

在服务端,我正在尝试使用以下代码获取Cookie

private final String cookieName = "RSOMyLogin";

    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
    public Object handleFileUpload(HttpServletRequest request, @FormDataParam("files") MultipartFile[] files,
            @FormDataParam("docType") String docType, @FormDataParam("fileMetadata") FileMetadata fileMetadata) {


        HttpSession session = request.getSession(false);
        String JSession = "";
        Cookie[] cookie = request.getCookies();
        System.out.println("cookie: "+cookie); //prints nothing
        for (int i = 0; i < cookie.length; i++) { //java.lang.NullPointerException: null
            if (cookie[i].getName() != null && cookie[i].getName().equalsIgnoreCase(cookieName)) {
                JSession = cookie[i].getValue();
            }
        }

获取Cookie时我是否缺少任何东西,或者我无法正确设置它们?

还是我完全偏离了轨道:(

在服务器代码中,您正在寻找名称为RSOMyLogin的cookie。 为了使其正常工作,请在客户端代码中使用context属性而不是cookie名称设置cookie存储:

localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore)

它取代了旧的和过时的:

localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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