URL에서 파일을 다운로드 할 수있는 프로그램을 Java로 작성하려고합니다. 대신 URLConnection을 사용하지 않고이 작업을 수행하려고합니다. 대신 TCP 소켓 만 사용하고 있습니다. GET 요청을 보내고 서버의 응답을 얻는 데 성공했지만 HTTP 헤더 (파일 만)가없는 응답에서 파일을 저장하지 못하는 것 같습니다.헤더를 포함하지 않고 HTTP 응답에서 보낸 파일을 저장하는 방법
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 응답을 포함하는 파일을 생성합니다.
사실, 자신의 HTTP 스택을 롤업하려면 RFC를 따라야합니다. http://www.w3.org/Protocols/rfc2616/rfc2616.html – home