Ars*_*ine -4 java sockets inputstream
我使用以下代码使用socket而不是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);
}
Run Code Online (Sandbox Code Playgroud)
这是:
for(int x=0;fileData[x]>0;x++){
Run Code Online (Sandbox Code Playgroud)
对 ?看起来你正试图根据流的内容进行破解.正如Flavio所指出的那样,由于新创建了数组,因此该语句立即失效.
我认为你更有可能阅读指定的内容长度,或者直到达到流的末尾.
实际上,我更倾向于使用现有的HttpClient并绕过上述所有内容.编写可靠的HTTP代码并不像第一次出现那样简单,第三方库会为您节省很多麻烦.
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |