以下代码存在一些问题:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
class Main {
public static void main(String args[]) {
try {
Socket s = new Socket("ark.intel.com", 80);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.write("GET / HTTP/1.1\r\n"
+ "Host: ark.intel.com\r\n"
+ "Connection: keep-alive\r\n"
+ "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\r\n"
+ "Accept: text/html"
+ "\r\n");
out.flush();
BufferedReader read = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
String data = "";
while ((line = read.readLine()) != null) {
data += line;
System.out.println(line);
} read.close();
} catch (Exception error) {}
}
}
我不断得到
HTTP/1.0 408 请求超时 服务器:AkamaiGHost Mime 版本:1.0 日期:2018 年 2 月 6 日星期二 11:43:41 GMT 内容类型:text/html 内容长度:218 到期时间:2018 年 2 月 6 日星期二 11:43:41 GMT
<HTML><HEAD>
<TITLE>Request Timeout</TITLE>
</HEAD><BODY>
<H1>Request Timeout</H1>
The server timed out while waiting for the browser's request.<P>
Reference #2.403b3717.1517917421.0
</BODY></HTML>
知道如何解决这个问题吗?
编辑: 主机 ark.intel.com 使用 HTTPS,我需要找到一种通过 HTTPS 而不是 HTTP 发送请求的方法。
最佳答案
缺少\r\n:
+ "Accept: text/html\r\n"
更新
正如我们所见,这将允许您执行请求,但您将获得重定向,迫使您使用 HTTPS。
尝试使用 HttpURLConnection
而不是普通套接字:
try {
URL url = new URL("https://ark.intel.com/");
HttpURLConnection cnt = (HttpURLConnection) url.openConnection();
cnt.setRequestProperty("Host", "ark.intel.com");
cnt.setRequestProperty("Connection", "keep-alive");
cnt.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
cnt.setRequestProperty("Accept", "text/html");
int stat = cnt.getResponseCode();
if (stat != 200) {
throw new IOException("HTTP error " + stat);
}
BufferedReader read = new BufferedReader(new InputStreamReader(cnt.getInputStream()));
String line;
String data = "";
while ((line = read.readLine()) != null) {
data += line;
System.out.println(line);
} read.close();
} catch (Exception error) {
error.printStackTrace();
}
关于java - 请求超时-socket Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48642339/