【问题标题】:URL.openStream very slowURL.openStream 很慢
【发布时间】:2012-06-15 20:22:24
【问题描述】:

我正在从 SQL 数据库下载安卓设备上的图片;一切正常,除了打开 Stream 需要很长时间(即使没有图片可下载)。在实际下载开始之前大约需要 5 秒。这是我的代码 sn-p:

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()); 行给出了问题。关于如何加快速度的任何想法?

【问题讨论】:

  • 您确定延迟发生在该语句中吗?我原以为它会发生在connect() 电话中。

标签: java android url upload inputstream


【解决方案1】:

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

【讨论】:

  • 实际上,TCP 连接是提前一两个声明的......因为他会得到内容长度。但您可能是对的,这只是网络延迟,Java 客户端代码中没有解决此问题的方法。
  • @StephenC 是的。在这种情况下,必须是 getContentLength() 花费时间。
【解决方案2】:

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

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-3 秒.. 谢谢!也许使用 HTTPURLConnection 可以加快速度..
  • @user1337210 不,您已经在使用它了。这里唯一的区别是类型转换。这里没有任何东西可以回答这个问题。
【解决方案3】:

您在创建InputStream 时调用url.openStream(),但在此之前您要创建新连接并调用connection.connect()

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

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

总的来说,我认为您应该在初始化InputStream 时调用connection.getInputStream()

【讨论】:

  • 这两个事件无论如何都会发生。如果您不明确执行连接,则连接是隐式的。请参阅 Javadoc。
猜你喜欢
  • 1970-01-01
  • 2012-12-29
  • 2014-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2011-03-08
相关资源
最近更新 更多