java - 使用 POST 方法时的 HTTPClient 重定向

标签 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();
        }


    }
}

最佳答案

自动重定向 POST 请求违反 RFC 标准。因此,HttpClient 默认情况下不会执行此操作。然而根据DefaultRedirectStrategy的API这可以通过使用 LaxRedirectStrategy 来实现.

在代码中,这看起来像:

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

关于java - 使用 POST 方法时的 HTTPClient 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20009405/

相关文章:

Java注入(inject)最终属性

java - 如何使用 sbt 和 Java 1.8 生成能够在 Java 1.7 上运行的 jar 文件

post - PHP POST 推荐人

java - 输入凭据,然后将 JSON 发布到 api java

.htaccess - 无法访问我的 Magento 文件夹中的 Magmi 子文件夹

java - Anagram Checker 解决管测验

java - 我已声明为同步的保护方法,但它给出的输出似乎是该方法未同步

java - 在Java中发送HTTP POST请求

Rails 重定向后 Javascript 未执行

php - htaccess ErrorDocument 404重定向不起作用