從this question嘗試此代碼。當請求stackoverflow.com
時,它給出了正確的答覆,但是當我嘗試https://stackoverflow.com/questions/10673684/send-http-request-manually-via-socket
時,它返回HTTP/1.1 400 Bad Request
。什麼導致這個問題?Java套接字獲取HTTP/1.1 400錯誤請求
這是我從上面的鏈接得到的正確的響應從服務器得到的工作代碼。
Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("GET/HTTP/1.1");
pw.println("Host: stackoverflow.com");
pw.println("");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String t;
while ((t = br.readLine()) != null) {
System.out.println(t);
}
br.close();
試圖將其更改爲以下...
Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("GET/HTTP/1.1");
pw.println("Host: https://stackoverflow.com/questions/10673684/send-http-request-manually-via-socket");
pw.println("");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String t;
while ((t = br.readLine()) != null) {
System.out.println(t);
}
則響應爲HTTP/1.1 400 Bad Request
。
P.S.我不打算使用任何http庫。
主機應該保持在工作代碼中,但您必須將主機上方的行更改爲GET/questions/10673684/send-http-request-manually-via-socket HTTP/1.1' – Alex
@Alex您應該將該評論作爲回答 – tddmonkey
Hi @Alex。你是對的。非常感謝。如果你會提出答案,我會標記它。 – beginner