android - 使用带有 HttpURLConnection 的 POST 发送文件

标签 android http post client-server httpurlconnection

自 Android 开发者 recommend要使用 HttpURLConnection 类,我想知道是否有人可以为我提供一个很好的示例,说明如何通过 POST 将位图"file"(实际上是内存中的流)发送到 Apache HTTP 服务器。我对 cookie 或身份验证或任何复杂的东西不感兴趣,但我只想拥有一个可靠且符合逻辑的实现。我在这里看到的所有示例看起来更像是“让我们试试这个,也许它会起作用”。

现在,我有这个代码:

URL url;
HttpURLConnection urlConnection = null;
try {
    url = new URL("http://example.com/server.cgi");

    urlConnection = (HttpURLConnection) url.openConnection();

} catch (Exception e) {
    this.showDialog(getApplicationContext(), e.getMessage());
}
finally {
    if (urlConnection != null)
    {
        urlConnection.disconnect();
    }
}

其中 showDialog 应该只显示一个 AlertDialog(如果 URL 无效?)。

现在,假设我生成了一个像这样的位图: Bitmap image = this.getBitmap() 在从 View 派生的控件中,我想通过它发送它邮政。实现这样的事情的正确程序是什么?我需要使用哪些类?我可以像在 this example 中那样使用 HttpPost 吗? ?如果是这样,我将如何为我的位图构造 InputStreamEntity?我会发现要求首先将位图存储在设备上的文件中是令人反感的。


我还应该提到,我确实需要将原始位图的每个未更改的像素发送到服务器,所以我无法将其转换为 JPEG。

最佳答案

我不知道为什么 HttpURLConnection类不提供任何发送文件的方法,而无需手动编写文件包装器。这是我最终做的,但如果有人知道更好的解决方案,请告诉我。

输入数据:

Bitmap bitmap = myView.getBitmap();

静态的东西:

String attachmentName = "bitmap";
String attachmentFileName = "bitmap.bmp";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

设置请求:

HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://example.com/server.cgi");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDoOutput(true);

httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.setRequestProperty(
    "Content-Type", "multipart/form-data;boundary=" + this.boundary);

启动内容包装器:

DataOutputStream request = new DataOutputStream(
    httpUrlConnection.getOutputStream());

request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" +
    this.attachmentName + "\";filename=\"" + 
    this.attachmentFileName + "\"" + this.crlf);
request.writeBytes(this.crlf);

转换 BitmapByteBuffer :

//I want to send only 8 bit black & white bitmaps
byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
for (int i = 0; i < bitmap.getWidth(); ++i) {
    for (int j = 0; j < bitmap.getHeight(); ++j) {
        //we're interested only in the MSB of the first byte, 
        //since the other 3 bytes are identical for B&W images
        pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
    }
}

request.write(pixels);

结束内容包装:

request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary + 
    this.twoHyphens + this.crlf);

刷新输出缓冲区:

request.flush();
request.close();

得到响应:

InputStream responseStream = new 
    BufferedInputStream(httpUrlConnection.getInputStream());

BufferedReader responseStreamReader = 
    new BufferedReader(new InputStreamReader(responseStream));

String line = "";
StringBuilder stringBuilder = new StringBuilder();

while ((line = responseStreamReader.readLine()) != null) {
    stringBuilder.append(line).append("\n");
}
responseStreamReader.close();

String response = stringBuilder.toString();

关闭响应流:

responseStream.close();

关闭连接:

httpUrlConnection.disconnect();

PS:当然,我必须将请求包装在 private class AsyncUploadBitmaps extends AsyncTask<Bitmap, Void, String> 中。 ,为了让Android平台开心,因为它不喜欢在主线程上有网络请求。

关于android - 使用带有 HttpURLConnection 的 POST 发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11766878/

相关文章:

android - 如何避免多模块android应用程序中的重复依赖

java - android上的图像分割

php - 使用 jquery 的 .post 上传文件

http - 如何测试 multipart/form-data POST 请求

java - 如何在点击 Android 应用程序中的任何按钮时禁用音频?

http - DNS 请求(例如 txt 记录)是否可以用于提供 .css 和 .js 文件?

java - Apache Camel http 到 http 路由以及响应转换

spring - 使用 Angular2 将 MultipartFile 作为请求参数发送到 REST 服务器

javascript - Html POST 并返回与值相同的形式

android - 将 Object[] 转换为 ContentValues[] 时出错