为每个用户设置servlet java HttpURLConnection中的Cookie



我有一个API servletjava应用程序,用户可以通过他的用户和密码查看外部页面,查看URL需要在调用之前设置cookie

我使用此代码查看页面

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
String request_url = "http://url/view.jsp?id"+ id;
URL url = new URL(request_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setInstanceFollowRedirects(false);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setReadTimeout(20000);
httpURLConnection.connect();
try (BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
data = data + inputLine;
helper.status = 0;
helper.errorDesc = "0";
}
in.close();
}
httpURLConnection.disconnect();

如果它没有返回访问数据,我使用此代码使用用户凭据登录

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
String urlParameters = "username=" + username + "&password=" + password + "&displayLangCode=" + lang  + "&langCode=" + lang;
System.out.println("urlParameters" + urlParameters);
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String activeUrl = "http://url/login.jsp";
URL url = new URL(activeUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("X-Service", "AuthenticateUser");
httpURLConnection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
httpURLConnection.setInstanceFollowRedirects(false);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(20000);
httpURLConnection.setReadTimeout(20000);
httpURLConnection.connect();
try (DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream())) {
wr.write(postData);
wr.close();
}
httpURLConnection.disconnect();

它运行良好,我可以获取内容,

问题是,如果另一个用户打电话查看内容,他可以作为第一个登录的用户查看内容

这意味着cookie是由API级别设置的,而不是由用户级别、设置的

我需要帮助,因为我不知道如何解决这个cookie问题,以设置每个用户调用的cookie

我可以通过禁用自动cookie 来解决这个问题

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_NONE);

然后在登录方法中,我提取cookie并从函数返回

List<String> cookies = httpURLConnection.getHeaderFields().get("Set-Cookie");
String token = null;
if (cookies != null) {
for (String cookie : cookies) {
token = cookie.split(";", 1)[0];
}
}
return token

然后每次调用view函数时,我们都会传递cookie

httpURLConnection.addRequestProperty("Cookie", token);

最新更新