使用POST方法时的HTTPClient重定向

时间:2013-11-15 19:49:06

标签: java post redirect httpclient

我有一个网站使用此PHP代码将我重定向到另一个网站:

<?php
    header("Location: new.php?id=".$_POST["id"]."&test=".rand(5,15));
    echo "35";
?>

-new.php

<?php
    echo "ID: ".$_GET["id"]."| TEST: ".$_GET["test"];
?>

如果我尝试使用HTTPClient发送Post请求,则该站点不会将我重定向到其他站点(post请求的响应为35)。当我发送Get请求时,它工作得很好。请求的响应是ID:|测试:13。

-http.java

public class Http {
    public static void main(String[] args) {
        HttpResponse response;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost post = new HttpPost("http://localhost/test.php");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("id","55"));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            response = client.execute(post);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            HttpGet get = new HttpGet("http://localhost/test.php");
            response = client.execute(get);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

1 个答案:

答案 0 :(得分:3)

自动重定向POST请求是违反RFC标准的。因此,HttpClient默认不会这样做。但是,根据DefaultRedirectStrategy的API,可以使用LaxRedirectStrategy来实现。

在代码中,这看起来像是:

  DefaultHttpClient httpClient = new DefaultHttpClient();
  httpClient.setRedirectStrategy(new LaxRedirectStrategy());
  httpClient.execute(request);