在Android中通过移动网络将图像缓慢上传到服务器

时间:2014-01-25 22:46:26

标签: android http networking android-wifi

我尝试通过移动网络将图像上传到服务器,上传速度非常慢。如果我换成WIFI,那就更好了。你能给我一个如何解决这个问题的建议吗?我知道细胞网络很糟糕,但我的图像不超过90 kb。

我使用httpurlconnection和MultipartEntity。

private synchronized final void createPart(String partName, String fileName, String imagePath, MultipartEntity entity) {
    WidthHeight sizes = ImageSizeConstants.getDefaultSize().getWidthHeight();
    Bitmap loaded = BitmapUtil.loadBitmapFromFile(imagePath, sizes.width, sizes.height);
    Bitmap bitmap = Bitmap.createScaledBitmap(loaded, sizes.width, sizes.height, true);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bos);

    bitmap.recycle();
    bitmap = null;
    loaded.recycle();
    loaded = null;
    byte[] content = bos.toByteArray();
    ContentBody contentPart = new ByteArrayBody(content, Constants.IMAGE_JPEG_MIME_TYPE, fileName);
    entity.addPart(partName, contentPart);
}

protected int getConnectTimeout() {
    return 50000;
}

protected int getReadTimeout() {
    return 60000;
}

@Override
protected HttpURLConnection initConnection(HttpURLConnection connection) throws IOException {
    super.initConnection(connection);

    connection.setUseCaches(false);
    connection.setConnectTimeout(getConnectTimeout());
    connection.setReadTimeout(getReadTimeout());
    connection.setRequestProperty(CONNECTION_TYPE, CONNECTION_TYPE_CLOSE);

    return connection;
}

@Override
protected void setupConnection(HttpURLConnection connection, QueryBuilder builder, Integer httpStatusCode) throws IOException, BadResponseStatusCodeException {
    MultipartEntity reqEntity = builder.getEntity();
    addBuilderDataParams(builder, reqEntity);

    connection = initConnection(connection);

    connection.addRequestProperty(CONTENT_LENGTH, Long.toString(reqEntity.getContentLength()));
    connection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

    OutputStream os = connection.getOutputStream();
    reqEntity.writeTo(connection.getOutputStream());
    os.close();
    connection.connect();

    httpStatusCode = connection.getResponseCode();
    checkStatusCode(httpStatusCode);

    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line;
    StringBuilder response = new StringBuilder();

    while ((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }

    rd.close();
    is.close();
    String responseStr = response.toString().replace(QUOT, QUOT_REPLACE_VALUE);
    initResponse(responseStr);
}

我注意到在H +模式的蜂窝网络中,发送需要5秒,这对我的应用来说真的很好。有没有办法优化发送图像的大小?

谢谢

0 个答案:

没有答案