【问题标题】:HTTPURLConnection.getInputStream() Takes a very long time?HTTPURLConnection.getInputStream() 需要很长时间?
【发布时间】:2011-11-20 03:54:35
【问题描述】:

我正在使用 HttpURLConnection 上传图像文件,对于包含所有标题的 5MB 文件大约需要 3 秒,但是当我使用 .getInputStream() 打开 InputStream 时,该方法需要大约 8 秒以上才能返回流。这是一个问题,因为如果我要上传多张图片,上传进度条的用户体验似乎很差,每次上传之间都有相当长的停顿,所以进度条在上传之间只会停止几秒钟。我做了一些谷歌搜索,但似乎没有其他人对此有问题?

通常我会假设服务器很慢,但鉴于上传只需要几秒钟,下载“成功”或“失败”这个词应该不是什么大问题!

这里有一些代码!我一开始是不是设置错了什么? 注意:这也在 AsyncTask 中

    ByteArrayInputStream fileInputStream = null;

    try {
        fileInputStream = new ByteArrayInputStream(dObject.Data);

    } catch (Exception e) {
        e.printStackTrace();
    }


    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    String Tag="3rd";
    try
    {
        //------------------ CLIENT RE QUEST        
        Log.e(Tag,"Inside second Method");      

        // Open a HTTP connection to the URL    
        URL url = new URL(_urlString);
        //connectURL is a URL object
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "Keep-Alive");

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

        DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        //dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + _fileLocation +"\"" + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + _fileLocation +"\"" + lineEnd);

        dos.writeBytes(lineEnd);

        Log.e(Tag,"Headers are written");

        // create a buffer of maximum size
        int bytesAvailable = fileInputStream.available();
        int maxBufferSize = 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];



        // read file and write it into form...  
        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);


        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);

            //int value = (int)(((float)((float)totalRead / (float) fileSize)) * 100);

            totalRead += bytesRead;
            //Publish the progress out to be displayed
            publishProgress(totalRead);



            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


        // close streams
        Log.e(Tag,"File is written");
        fileInputStream.close();
        dos.flush();

        Log.e("TIME", "PRE GETINPUTSTREAM");
        InputStream is = conn.getInputStream(); 
        Log.e("TIME", "POST GETINPUTSTREAM");
        //  retrieve the response from server
        int ch;


        //Build the respose and log
        StringBuilder b =new StringBuilder();
        while( ( ch = is.read() ) != -1 ){
            b.append( (char)ch );
        }
        String s=b.toString();      
        Log.i("Response",s);
        dos.close();

        return;
    }
    catch (MalformedURLException ex)
    {
        ErrorHandler.get().e("3");
    }

    catch (IOException ioe)
    {
        ErrorHandler.get().e("2");
    }

【问题讨论】:

    标签: java android httpurlconnection


    【解决方案1】:

    在我的例子中,我发现 getInputStream 看起来很慢,因为这个方法初始化了 ssl 握手(在 https URL 调用上)。第一次通话后,其他通话正常

    【讨论】:

      【解决方案2】:

      通常我会假设服务器很慢,但鉴于上传只需要几秒钟,下载“成功”或“失败”这个词应该不是什么大问题!

      我怀疑确实是服务器速度慢或过载。

      • 服务器可能正在对 HTTP 请求进行排队,并且一次只能并行处理少量请求。

      • 或者在将包含文件的响应写入响应之前执行的某些数据库活动可能存在瓶颈。

      • 或者它可以在运行中将文件生成到内存缓冲区(慢),然后从缓冲区流式传输(快)到 HTTP 响应。

      • 或者其他类似的解释...

      (理论上也有可能发生了一些有趣的事情,这会减慢将请求传递到服务器的速度。不过我认为这不太可能。)


      您是否尝试过使用网络浏览器下载相同的文件?你有同样的行为吗?

      【讨论】:

      • 确实是服务器变慢了..我不得不在上传时说“正在上传”,然后在等待服务器响应时显示一个带有“正在完成”的不确定进度条!我认为我的公司应该升级托管!
      猜你喜欢
      • 2014-05-29
      • 2013-09-07
      • 2020-08-26
      • 2014-10-09
      • 2012-11-26
      • 2019-12-27
      • 2017-10-22
      • 2020-11-15
      • 2016-05-19
      相关资源
      最近更新 更多