Java 如何从http服务器检索重定向url。?

Java 如何从http服务器检索重定向url。?,java,Java,当我执行HTTP post请求时,我得到的响应代码是200,而不是3xx,即使网页会自动重定向。我试过了,但没用。我的代码: HttpURLConnection con = getMultipartHttpURLConnection( formParameter.getServerUrl(), boundary); setRequestHeaders(con); String urlParameters = getParameter(formParameter.getForm()

当我执行HTTP post请求时,我得到的响应代码是200,而不是3xx,即使网页会自动重定向。我试过了,但没用。我的代码:

HttpURLConnection con = getMultipartHttpURLConnection(
        formParameter.getServerUrl(), boundary);
setRequestHeaders(con);
String urlParameters = getParameter(formParameter.getForm());
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
responseCode = con.getResponseCode();
String header = con.getHeaderField("Location");
编辑:


通过一些研究,我发现如果服务器被配置为重定向到启用了https://的url,那么我会得到
3xx
作为响应代码,否则就不会了。上面的链接中给出的示例也是如此

这是因为
HttpURLConnection
是智能的,在内部处理重定向。
200
响应代码是发生重定向的新位置的响应代码

我知道如何检索重定向URL的唯一方法是使用
setFollowRedirects(false)
并手动执行重定向

请参见以下示例:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetRedirectURL {
    public static void main(final String... args) throws IOException {
        final URL url = new URL("http://www.google.com/");
        //HttpURLConnection.setFollowRedirects(false);
        final HttpURLConnection con = (HttpURLConnection) url.openConnection();
        //con.setInstanceFollowRedirects(false);
        final int responseCode = con.getResponseCode();
        final String location = con.getHeaderField("Location");
        System.err.format("%d%n%s%n", responseCode, location);
    }
}
如果不修改此代码,它将打印
200 null
。如果取消对控制重定向行为的任何行的注释,则输出将更改为“200…”


重要的是,修改重定向设置必须在
HttpURLConnection
实例的状态机通过读取响应的方法调用发送请求之前完成。

Ok,但是如何读取重定向url以及如何检查重定向url是否存在。请参阅我刚才所做的编辑,我忘记了原来的问题,因为它没有在文本中重复。我尝试了两个连接。setInstanceFollowRedirects(true);HttpURLConnection.setFollowRedirects(true);两个都没用。请检查我编辑的有问题的链接。您是否使用
true
false
作为值?它必须是
false
,但是在你的评论中你写的是
true
。我试着同时使用true/false,但那也没什么区别。