Tôi muốn truy cập một trang web đầu tiên yêu cầu xác thực (máy chủ tomcat) và sau đó đăng nhập bằng yêu cầu POST và giữ người dùng đó xem các trang của trang web đó. Tôi sử dụng HttpClient 4.0.1Httpclient 4, lỗi 302. Cách chuyển hướng?
Việc xác thực đầu tiên hoạt động tốt nhưng không phải là đăng nhập luôn phàn nàn về lỗi này: "302 Đã tạm thời dời"
tôi giữ cookie & tôi giữ một bối cảnh nhưng không có gì. Trên thực tế, có vẻ như đăng nhập hoạt động, bởi vì nếu tôi viết thông số không chính xác hoặc mật khẩu người dùng ||, tôi sẽ thấy trang đăng nhập. Vì vậy, tôi đoán những gì không hoạt động là chuyển hướng tự động.
Tiếp theo mã của tôi, mà luôn luôn ném IOException, 302:
DefaultHttpClient httpclient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
httpclient.getParams().setParameter(
ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
HttpContext context = new BasicHttpContext();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//ResponseHandler<String> responseHandler = new BasicResponseHandler();
Credentials testsystemCreds = new UsernamePasswordCredentials(TESTSYSTEM_USER, TESTSYSTEM_PASS);
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
testsystemCreds);
HttpPost postRequest = new HttpPost(cms + "/login");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("pUserId", user));
formparams.add(new BasicNameValuePair("pPassword", pass));
postRequest.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
HttpResponse response = httpclient.execute(postRequest, context);
System.out.println(response);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
throw new IOException(response.getStatusLine().toString());
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(
ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
String currentUrl = currentHost.toURI() + currentReq.getURI();
System.out.println(currentUrl);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len != -1 && len < 2048) {
System.out.println(EntityUtils.toString(entity));
} else {
// Stream content out
}
}
"Việc xác thực đầu tiên hoạt động tốt nhưng không phải là đăng nhập luôn phàn nàn về lỗi này". Chuyển hướng 302 không phải do máy chủ khiếu nại; nó là một dấu hiệu cho thấy tác nhân người dùng phải tiến hành trang mới được chỉ ra trong phản hồi. –
Tôi nghĩ vậy, nhưng làm sao? Tôi thử sau đó một yêu cầu GET nhưng vô ích. – juanmirocks