URL.openStream非常慢

时间:2012-06-12 21:46:49

标签: java android url upload inputstream

我正在从SQL数据库下载Android设备上的图片;一切都运作良好,除了打开流需要很长时间(即使没有图片下载)。在实际下载开始之前大约需要5秒钟。这是我的代码片段:

URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();

int fileLength = connection.getContentLength();

//input = connection.getInputStream();
InputStream input = new BufferedInputStream(url.openStream());


File file = new File(
        Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
        "MyCameraApp" + "/testpic.jpg");
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];

//---blabla progressbar update etc..

InputStream input = new BufferedInputStream(url.openStream());给出了问题。关于如何加快速度的想法?

3 个答案:

答案 0 :(得分:4)

这是创建实际TCP连接的点。这是一个网络问题,而不是编码问题。您无法在代码中执行任何操作来修复它。

答案 1 :(得分:3)

我使用此代码从网址获取位图。 :)

Bitmap bitmap = null;
    URL imageUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    InputStream is = conn.getInputStream();
    OutputStream os = new FileOutputStream(f);

try
{
   byte[] bytes=new byte[1024];
   for(;;)
   {
      int count=is.read(bytes, 0, 1024);
      if(count==-1)
         break;
      os.write(bytes, 0, count);
    }
 }
 catch(Exception ex){}
os.close();
bitmap = decodeFile(f); 

答案 2 :(得分:-1)

您在创建url.openStream()时呼叫InputStream,但在此之前您正在创建新连接并致电connection.connect()

来自android JavaDoc: openStream()是“等同于openConnection().getInputStream(types)

http://developer.android.com/reference/java/net/URL.html#openStream()

总之,我认为您在初始化connection.getInputStream()时应致电InputStream