我使用以下代码使用套接字而不是 url.openconnection() 从指定的 url 下载文件;下载后,当我检查它不起作用时...当我用编辑器打开文件时,它完全是空白的,文件内没有数据(空文件)需要建议???... ...
try {
String address="http://tineye.com/images/widgets/mona.jpg";
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);
OutputStreamWriter osw=new OutputStreamWriter(mysocket.getOutputStream());
osw.write("GET " + file + " HTTP/1.0\r\n\n");
osw.flush();
dis = new DataInputStream(mysocket.getInputStream());
fileData = new byte[7850];
for (int x = 0; fileData[x] > 0; x++){
fileData[x] = (byte) dis.read();
}
// close the data input stream
fos = new FileOutputStream(new File("C:\\Users\\down-to\\filedownloaded.jgp")); //create an object representing the file we want to save
fos.write(fileData); // write out the file we want to save.
dis.close();
fos.close();
} catch (UnknownHostException ex) {
Logger.getLogger(Check.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Check.class.getName()).log(Level.SEVERE, null, ex);
}