[英]Keep getting the same error code (bad request) when trying to retrieve a page using sockets
我試圖使用Socket獲取網頁並獲取請求,但我一直收到相同的錯誤-錯誤的請求,對於我嘗試使用的任何網站或網頁。
Socket s = new Socket("horstmann.com", 80);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
Scanner reader = new Scanner(in);
PrintWriter writer = new PrintWriter(out, false);
String command = "GET / HTTP/1.0\n\n";
//System.out.print(command);
writer.print(command);
writer.flush();
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
s.close();
嘗試這個 :
import java.net.*;
import java.io.*;
class ScoketQuestion {
public static void main(String[] args) {
try {
final String URL = "";
Socket s = new Socket(URL, 80);
DataInputStream dIn = new DataInputStream(s.getInputStream());
PrintWriter wtr = new PrintWriter(s.getOutputStream());
wtr.println("GET / HTTP/1.1");
wtr.println("Host: " + URL);
wtr.println("");
wtr.flush();
byte[] data = new byte[1024];
int pt = 0;
String str;
while (true) {
pt = dIn.read(data);
if (pt == -1) break;
str = new String(data, 0, pt);
System.out.println(str);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.