我想要訪問首先需要(tomcat服務器)身份驗證的一個站點,然後使用POST請求登錄並讓該用戶查看該站點的頁面。我使用的HttpClient 4.0.1Httpclient 4,錯誤302.如何重定向?
第一認證工作正常,但並不總是抱怨這個錯誤的登錄:「302臨時移動」
我把餅乾&我保持一個方面,但一無所獲。實際上,登錄似乎有效,因爲如果我寫入不正確的參數或用戶||密碼,我會看到登錄頁面。所以我猜想什麼是不工作的自動重定向。
繼我的代碼,它總是拋出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
}
}
「第一認證工作正常,但並不總是抱怨這個錯誤登錄」。 302重定向不是服務器的投訴;這表示用戶代理現在必須進入響應中指示的新頁面。 – 2010-09-07 12:48:11
我以爲那可是如何?我嘗試一個GET請求,但無濟於事。 – juanmirocks 2010-09-07 13:19:11