我想在此IP中从互联网上下载图片: http://redsonic.skyf.ir/testdownload.jpg
但我的httpurlConnection.getContentLength()
返回-1。
这是我的代码:
URL url = new URL(downloadPath);
HttpURLConnection httpConnection =(HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.connect();
File file = new File(filePath);
OutputStream outputStream = new FileOutputStream(file);
InputStream inputStream = httpConnection.getInputStream();
byte[] buffer = new byte[8*1024];
int len=0;
int downloadsize = 0;
int filesize = httpConnection.getContentLength();
while ((len=inputStream.read(buffer))>0)
{
outputStream.write(buffer,0,len);
downloadsize += len;
float persent = (float) downloadsize/filesize;
Log.i("***","downloadsize="+downloadsize + " filesize="+filesize+" percent = "+persent);
}
//outputStream.flush();
outputStream.close();
但是当我从互联网上下载其他图片时,它可以工作。
怎么可能?
答案 0 :(得分:0)
只需删除行:httpConnection.setDoOutput(true);
或设置为
答案 1 :(得分:-1)
没有错。我试过我的电脑。 httpurlConnection.getContentLength()返回847.如果请求过多,则可能超过了最大连接数。