我尝试使用套接字而不是 url 下载文件。使用以下代码,文件未完全下载,当我尝试打开文件时,它显示所选文件无法打开的消息...可以删除此错误通过使用 url.openconnection() 方法,但需要通过套接字完成....需要建议。
public class Check {
private String addres;
public void FileDownload(String urladd) {
try {
this.addres=urladd;
String address;
URL url_of_file=new URL(addres);
String hostaddress=url_of_file.getHost();
Socket mysocket=new Socket(hostaddress, 80);
System.out.println("Socket opened to " + hostaddress + "\n");
String file=url_of_file.getFile();
System.out.println(" file = "+file);
OutputStream os = mysocket.getOutputStream();
os.write(("GET " + file + " HTTP/1.0\r\n").getBytes("UTF-8"));
os.write(("HOST: " + hostaddress + "\r\n").getBytes("UTF-8"));
os.write(("\r\n").getBytes("UTF-8"));
os.flush();
String url = "C:\\Users\\Desktop\\file_downloaded.jpg";
File f=new File(url);
f.createNewFile();
OutputStream ops = new FileOutputStream(f);
byte data = 0;
InputStream in=mysocket.getInputStream();
data = (byte) in.read();
while (data != -1) {
ops.write(data);
data = (byte) in.read();
}
ops.flush();
ops.close();
mysocket.close();