所以我的作业就像标题所示。获取一个URL,从中获取主机名和路径名,然后打开一个套接字并写入/读取它。 我已经分割了网址并尝试制作套接字:
try {
Socket socket = new Socket(hostname, port);
InputStream inStream = socket.getInputStream();
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
outStream.writeChars(pathname);
outStream.flush();
}
catch (Exception e) {
System.out.println(e);
}
然后我尝试了很多方法来获得响应,例如我使用过:
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("test.txt")));
byte[] buf = new byte[256];
int n = 0;
while ((n=in.read(buf))>=0) {
out.write(buf, 0, n);
}
out.flush();
out.close();
除了许多其他变体之外,它们似乎总是陷入while循环。我应该将响应作为字节读取,然后将字节数组转换为字符串。为什么这会陷入while循环?
答案 0 :(得分:0)
我认为您的情况有误,应该是> 0而不是> = 0
答案 1 :(得分:0)
您必须发送有关HTTP协议的正确数据。试试这个
try {
String hostname = "stackoverflow.com";
String requestHeaders[][] = {
{ "Host" , hostname } ,
{ "User-Agent" , "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" } ,
};
String pathname = "questions/33047629/basic-http-client-from-scratch/33047769#33047769";
int port = 80;
Socket socket = new Socket(hostname, port);
InputStream inStream = socket.getInputStream();
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
String data = "GET /"+pathname+" HTTP/1.1\r\n";
for (int i=0;i<requestHeaders.length;i++){
data += requestHeaders[0]+": "+requestHeaders[1]+"\r\n";
}
data += "\r\n";
outStream.writeChars(data.getBytes());
outStream.flush();
}
catch (Exception e) {
System.out.println(e);
}
有一些浏览器插件显示浏览器发送的标头。您可以从插件中学习它们并实现它们,因为我实现了2个标题