我正在開發Java程序,目的是將從少數網站收集的數據集成到輸出中。我從這些網站獲得了API信息,並且我可以使用PHP輕鬆運行它們,但是當我嘗試使用Java時,只有其中一個網站存在一個奇怪的問題。我已經設置了遵循重定向的代碼,但是如果我試圖訪問https://www.foo.com,它會將我指向127.0.0.1。它可以做到這一點,無論我使用的協議或包含/不包含www。如果我拿出重定向代碼,我會生成一個通用的「永久移動」頁面。Java HttpGet重定向到127.0.0.1
這裏是我使用
public static void main(String args[]) throws IOException {
String URLString = "http://www.sickw.com/";
URL url = new URL(URLString);
URLConnection connection = url.openConnection();
System.out.println(url.toString()); //See what URL is being used
String redirect = connection.getHeaderField("Location");
while (redirect!=null)
{
System.out.println(redirect); //Follow the redirects
connection = new URL(redirect).openConnection();
redirect = connection.getHeaderField("Location");
}
System.out.println("new " + connection.getURL().toString()); //Print the final destination
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
int temp = inputStreamReader.read();
while(temp!=-1)
{
System.out.print((char)temp);
temp = inputStreamReader.read();
}
}
也許該網站有機器人檢測和重定向您根據您的用戶代理字符串。 –