这就是请求的样子(在顶部):
这是我的 Java 代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception{
URL url = new URL("http://ishin-global.aktsk.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("/ping ", " HTTP/1.1");
conn.setRequestProperty("Host"," ishin-global.aktsk.com");
conn.setRequestProperty("Accept"," */*");
conn.setRequestProperty("X-Platform"," android");
conn.setRequestProperty("X-ClientVersion"," 3.1.2");
conn.setRequestProperty("X-Language"," en");
conn.connect();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
问题是我没有从服务器得到响应,但我收到这些错误:
Exception in thread "main" java.io.FileNotFoundException: http://ishin-global.aktsk.com
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1836)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at Main.main(Main.java:24)
我一直无法弄清楚,所以我在这里问。提前谢谢
最佳答案
conn.setRequestProperty("/ping ", "HTTP/1.1");
不正确。 /ping
不是 HTTP 请求 header ,而是 URL 的路径。 URL 的路径是 URL 本身的一部分,而不是 header :
URL url = new URL("http://ishin-global.aktsk.com/ping");
删除 conn.setRequestProperty("/ping ", "HTTP/1.1");
行。 Java(以及每个 HTTP 客户端)在连接时将自动发送正确的初始行。
关于java - 连接 URL 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44950196/