【发布时间】:2019-08-27 14:49:36
【问题描述】:
我有一个 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 时有什么遗漏或者我无法正确设置它们吗?
或者我在这里完全偏离轨道:(
【问题讨论】:
标签: java rest spring-boot cookies httpclient