我正在开发 Ubuntu 12.04。这是我使用 URLConnection 实现 HTTP GET 方法的简单代码。
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "https://www.google.com/search?q=flower";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
但是当我从 ubuntu 终端编译并运行这段代码时,这段代码的输出并没有给出 URL 指定的页面内容。相反,它给出了以下输出
Testing 1 - Send Http GET request
Sending 'GET' request to URL : http://www.google.com/search?q=flower
Response Code : 307
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>307 Temporary Redirect</title></head><body><h1>Temporary Redirect</h1><p>The document has moved <a href="https://ifwb.iitb.ac.in/index.php?add=www.google.com/search">here</a>.</p><hr><address>Apache/2.2.22 (Fedora) Server at www.google.com Port 80</address></body></html>
这个问题适用于我在代码中指定的任何 URL。此外,我尝试使用 telnet 客户端访问 Web 内容,例如
远程登录 www.google.com 80 GET /
它不仅为 www.google.com 提供了类似的结果,而且为每个 URL 提供了类似的结果。我是 IIT Bombay 的学生,可能与https://ifwb.iitb.ac.in有关。我也想坚持 java.net 而不是 apache httpclient。所以帮我解决这个问题。