我有一个网站,它使用以下 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/