使用带有HttpURLConnection的POST发送文件

Mihai Todor

由于Android开发人员建议使用HttpURLConnection该类,所以我想知道是否有人可以向我提供一个很好的示例,说明如何通过POST将位图“文件”(实际上是内存中的流)通过POST发送到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,我想通过POST发送它。实现这种目标的正确程序是什么?我需要使用什么课程?我可以HttpPost此示例中使用吗?如果是这样,我将如何InputStreamEntity为我的位图构造我会发现首先将位图存储在设备上的文件中是必需的。


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

Mihai Todor

我不知道为什么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平台满意,因为它不希望在主线程上有网络请求。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

[Android]-带有HttpUrlConnection的POST Json

将带有 POST 请求的文件发送到 TelegramBot

在java中使用HttpURLConnection发送带有GET请求的请求正文

使用request.post发送带有证书的请求

使用Volley发送带有JSON数据的POST请求

使用Guzzle发送带有JSON的POST请求

使用Guzzlehttp发送带有JSON正文的POST请求

如何使用Volley发送带有JSON正文的POST请求?

如何使用Retrofit发送带有JSON的POST?

使用AJAX发送带有表单的表单文件时出错

带有图片/ jpeg的Android HttpURLConnection POST请求

Android:HttpUrlConnection使用POST发送请求正文(而不是GET)

使用HttpURLConnection发送帖子

Python发送带有标头的POST

FB API发送带有图像的POST

无法发送带有androidannotations的POST参数

无法发送带有正文的 POST

带有进度条的HttpUrlConnection分段文件上传

使用curl上传带有文件的POST数据

带有文件上传的提交表单不会在post变量中发送提交

Spring发送带有文件和输入ajax post值的formdata

在带有 redux 形式的 react js 中不使用 axios 发送 post 请求(在 post 请求中不发送任何内容)

使用React JS和Laravel将带有图像文件的POST请求发送到数据库时出现内部服务器错误

使用 J Meter 使用 Web-kit Form-Data 发送带有 POST 请求的参数

Android发送带有PDF文件的邮件

javascript发送带有文件的发布参数

发送带有文件附件的邮件

快速发送带有SFTP的CSV文件

带有Kotlin的Android-如何使用HttpUrlConnection