我正在尝试用 java 编写一个能够从 URL 下载文件的程序。我想在不使用 URLConnection 的情况下执行此操作,而我只是使用 TCP 套接字。我已成功发送 GET 请求并获取服务器的响应,但我似乎无法在没有 http-header(只是文件)的情况下从响应中保存文件。
import java.net.*;
import java.io.*;
public class DownloadClient {
public static void main(String[] args) {
try {
if (args.length != 3) {
System.out.println(
"Use: java DownloadClient <host> <port> <filename/path>"
);
} else {
// Sorting out arguments from the args array
String host;
int port;
String filename;
if (args[0].charAt(args[0].length()-1) == '/') {
host = args[0].substring(0,args[0].length()-1);
} else {
host = args[0];
}
port = Integer.parseInt(args[1]);
if (args[2].charAt(0) == '/') {
filename = args[2];
} else {
filename = "/"+args[2];
}
Socket con = new Socket(args[0], Integer.parseInt(args[1]));
// GET request
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(con.getOutputStream(), "UTF8")
);
out.write("GET "+filename+" HTTP/1.1\r\n");
out.write("Host: "+host+"\r\n");
out.write("User-Agent: Java DownloadClient\r\n\r\n");
out.flush();
InputStream in = con.getInputStream();
BufferedReader =
OutputStream outputFile = new FileOutputStream(
filename.substring(filename.lastIndexOf('/')+1)
);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while((bytesRead = in.read(buffer)) > 0) {
outputFile.write(buffer, 0, bytesRead);
buffer = new byte[1024];
}
outputFile.close();
in.close();
con.close();
}
} catch (IOException e) {
System.err.println(e);
}
}
}
我想我应该以某种方式寻找 \r\n\r\n 因为它表示内容开始之前的空行。到目前为止,这个程序创建了一个包含所有 http-response 的文件。