Android setChunkedStreamingMode()无法按预期工作

时间:2016-06-05 09:45:11

标签: android networking httpurlconnection

我在Android中使用HttpUrlConnection将大图像上传到服务器
一切都运作到目前为止,但发送有点慢...
我正在使用setChunkedStreamingMode()方法,因此我的旧设备在上传图像时不会耗尽内存。块大小目前设置为4MB

然而,我查看了Android的网络监视器并注意到我有很多小峰值,这不是我的预期 Network Monitor

据我所知,只要未达到块大小,OutputStream就应该读取字节数。达到块大小时,块将作为整体发送到服务器。但我不知道 获取网络监视器中的小峰值 我想我在这里错过了一些东西?

这是我的代码:

private final String boundary = "obzorBOUNDARYrozbo";
private final String mMimeType = "multipart/form-data;boundary=" + boundary;
private final String lineEnd = "\r\n";
private final String hyphens = "--";
private final String encoding = "utf-8";
private final String connectionType = "Keep-Alive";

...

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    // The body is sent in chunks of the defined size
    connection.setChunkedStreamingMode(Settings.__SendFileChunkSize);
    // Allows us to handle the response in the InputStream
    connection.setDoInput(true);
    // Allows us to write to the OutputStream
    connection.setDoOutput(true);
    // Disable the cache
    connection.setUseCaches(false);
    // Sets the request method to POST
    connection.setRequestMethod("POST");
    // Writes all Cookies written in the CookieManager to the header
    connection.setRequestProperty(
            "Cookie",
            TextUtils.join(";", cookieManager.getCookieStore().getCookies())
    );
    // The connection should be kept alive
    connection.setRequestProperty("Connection", connectionType);
    // Set the charset to UTF-8
    connection.setRequestProperty("Charset", encoding);
    // The type is defined to be a multipart request
    connection.setRequestProperty("Content-Type", mMimeType);
    connection.setConnectTimeout(1000);

...

BufferedInputStream bis = new BufferedInputStream(
            new FileInputStream(file),
            Settings.__SendFileBufferSize
    );

    // Check if less than maxBufferSize bytes are remaining
    int bytesAvailable = bis.available();
    // Do not read more bytes than maxBufferSize
    int bufferSize = Math.min(bytesAvailable, Settings.__SendFileBufferSize);

    byte[] buffer = new byte[bufferSize];
    while (bis.read(buffer, 0, bufferSize) > 0) {
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = bis.available();
        bufferSize = Math.min(bytesAvailable, Settings.__SendFileBufferSize);
    }
    bis.close();
    bis = null;
    buffer = null;

以下是我的块大小和缓冲区大小的常量

public static final int __SendFileChunkSize = 1024 * 1024 * 4;
public static final int __SendFileBufferSize = 1024 * 1024 * 4;

我要上传的图片大约是8MB

0 个答案:

没有答案