Httpclient 4,错误302.如何重定向?

jua*_*cks 22 java authentication post httpclient http-status-code-302

我想访问一个首先需要(tomcat服务器)身份验证的站点,然后使用POST请求登录并让该用户查看该站点的页面.我使用Httpclient 4.0.1

第一次身份验证工作正常但不是总是抱怨此错误的登录:"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
        }
    }
Run Code Online (Sandbox Code Playgroud)

fvi*_*cot 37

对于4.1版本:

DefaultHttpClient  httpclient = new DefaultHttpClient();
    httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {                
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)  {
            boolean isRedirect=false;
            try {
                isRedirect = super.isRedirected(request, response, context);
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 301 || responseCode == 302) {
                    return true;
                }
            }
            return isRedirect;
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 我不认为这应该返回false,我认为它应该返回isRedirect.当我进行此更改时,此代码有效.谢谢! (3认同)
  • 它可以工作,但在大多数情况下,http请求将POST请求更改为GET请求.如果目标(例如servlet)仅接受POST请求,则自动重定向将失败,状态代码为405(不允许方法).有什么建议? (3认同)

Ali*_*rme 19

对于HttpClient 4.3.x:

HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
Run Code Online (Sandbox Code Playgroud)


小智 18

在HttpCLient(4.1+)的更高版本中,您可以这样做:

DefaultHttpClient client = new DefaultHttpClient()
client.setRedirectStrategy(new LaxRedirectStrategy())
Run Code Online (Sandbox Code Playgroud)

LaxRedirectStrategy将自动重定向HEAD,GET和POST请求.要进行更严格的实现,请使用DefaultRedirectStrategy.

  • 这不是在 4.1 中引入的,而是在 4.2 中引入的。 (2认同)

Sha*_*ore 5

您必须实现自定义重定向处理程序,该处理程序将指示对POST的响应是重定向.这可以通过重写isRedirectRequested()方法来完成,如下所示.

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectHandler(new DefaultRedirectHandler() {                
    @Override
    public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
        boolean isRedirect = super.isRedirectRequested(response, context);
        if (!isRedirect) {
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode == 301 || responseCode == 302) {
                return true;
            }
        }
        return isRedirect;
    }
});
Run Code Online (Sandbox Code Playgroud)

在HttpClient的更高版本中,类名是DefaultRedirectStrategy,但可以在那里使用类似的解决方案.