使用 httpurlconnection 和 android 上传图像字节数组

nil*_*ash 3 android content-type httpurlconnection mime-types

我正在开发小型 android 应用程序,我想在其中将图像从我的 android 设备上传到我的服务器。我正在使用HttpURLConnection它。

我正在通过以下方式执行此操作:

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);

byte[] data = bos.toByteArray();

connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod(method.toString());

ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
bout.write(data); 
bout.close();
Run Code Online (Sandbox Code Playgroud)

我正在使用,ByteArrayOutputStream但我不知道如何使用我的 httpurlconnection 传递该数据。这是传递原始图像数据的正确方法吗?我只想发送包含图像数据的字节数组。没有转换或没有多部分发送。我的代码工作正常,没有任何错误,但我的服务器给了我答复 {"error":"Mimetype not supported: inode\/x-empty"}

我用 httpclient 做了这个,setEntity它可以很好地工作。但我想使用 urlconnection。

难道我做错了什么?这该怎么做?谢谢你。

San*_*ago 5

您必须打开输出流连接并将数据写入其中。你可以试试这个:

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float);

connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "image/jpeg");
connection.setRequestMethod(method.toString());
OutputStream outputStream = connection.getOutputStream();

ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream);
bitmap.compress(CompressFormat.JPEG, 100, bos);

bout.close();
outputStream.close();
Run Code Online (Sandbox Code Playgroud)

有了这个声明:

bitmap.compress(CompressFormat.JPEG, 100, bos);
Run Code Online (Sandbox Code Playgroud)

您正在做两件事:压缩位图并将结果数据(构建 jpg 的字节)发送到 bos 流,将结果数据发送到输出流连接。

您也可以直接在连接的输出流中写入数据,替换为:

ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream);
bitmap.compress(CompressFormat.JPEG, 100, bos);
Run Code Online (Sandbox Code Playgroud)

有了这个:

bitmap.compress(CompressFormat.JPEG, 100, outputStream);
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助您了解 HttpUrlConnection 的工作原理。

此外,您不应完全加载整个位图以避免“内存不足”异常,例如,使用流打开位图。