java.net.SocketInputStream.socketRead0(本机方法)

时间:2013-01-15 08:15:07

标签: java httpwebrequest serversocket

HttpURLConnection uc = null ;
URLPath = "";
URL url = new URL(URLPath);
uc = (HttpURLConnection) url.openConnection();
uc.setReadTimeout(10000);
uc.connect();
FileOutputStream fos = new FileOutputStream(savePath);
InputStream in = uc.getInputStream();
byte[] buffer = new byte[1024];
int Length = 0;
long FinishedLenth = 0;

while((Length = in.read(buffer)) > 0) {
    FinishedLenth = FinishedLenth + Length;
    fos.write(buffer, 0, Length);
}
uc.disconnect();
in.close();
fos.close(); 

这是我的功能代码,如果网络断开,则 代码将转到例外 我将异常写入重试功能。
userValue = 0,表示重试,1表示取消。

int userValue = gm.GetIt("Error");
if(userValue == 0){
 gp.interrupt();
 uc.disconnect();
 downloadFile(local,nas,ip,id,pw,fileId,index);
}
else{
 conf.downloadState.get(index).setpercent("fail");
 return false;
}
嗨,我有麻烦。
我编写代码,下载功能 如果网络断开,用户可以选择重试或取消 但是我收到了错误消息。

java.net.SocketTimeoutException: Read timed out  
    at java.net.SocketInputStream.socketRead0(Native Method)  
    at java.net.SocketInputStream.read(Unknown Source)  
    at java.io.BufferedInputStream.fill(Unknown Source)  
    at java.io.BufferedInputStream.read1(Unknown Source)  
    at java.io.BufferedInputStream.read(Unknown Source)  
    at sun.net.www.MeteredStream.read(Unknown Source)  
    at java.io.FilterInputStream.read(Unknown Source)  
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)  
    at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)  
    at Download_File.downloadFile(Download_File.java:54)  
    at downloadFileFunctionThread.run(downloadFileFunctionThread.java:113)  

第54行是while(......)。

2 个答案:

答案 0 :(得分:0)

尝试设置HttpURLConnection的{​​{3}}并尝试重新设计您的while循环,如:

//...
boolean connected = false;
boolean retry = false;

while(!connected & retry) {
    retry = askUserIfHeWantsToRetry();
    connected = uc.connected();
    URL url = new URL(URLPath);
    uc = (HttpURLConnection) url.openConnection();
    uc.setReadTimeout(10000);
    uc.connect();
}
//...

答案 1 :(得分:0)

检查你的java参数

它也可以设置如下

-Dsun.net.client.defaultConnectTimeout = 12345 -Dsun.net.client.defaultReadTimeout = 67890