发送使用POST文件的HttpURLConnection [英] Sending files using POST with HttpURLConnection

查看:256
本文介绍了发送使用POST文件的HttpURLConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Android开发建议使用的HttpURLConnection 类,我想知道是否有人能为我提供了如何通过POST发送一个位图文件(实际上是在内存流)到Apache HTTP服务器的一个很好的例子。我不感兴趣的饼干或认证或复杂的事情,但我只是希望有一个可靠的和逻辑的实现。所有这一切我已经看到了在这里看起来更​​像是范例,让我们试试这个,也许它的工作原理。

Since the Android developers recommend to use the HttpURLConnection class, I was wondering if anyone can provide me with a good example on how to send a bitmap "file" (actually an in-memory stream) via POST to an Apache HTTP server. I'm not interested in cookies or authentication or anything complicated, but I just want to have a reliable and logic implementation. All the examples that I've seen around here look more like "let's try this and maybe it works".

现在,我有这个code:

Right now, I have this code:

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 (如果一个无效的网址?)。

where showDialog should just display an AlertDialog (in case of an invalid URL?).

现在,让我们说,我产生一个位图,如下所示:位图图像= this.getBitmap()派生的控件查看<内部/ code>,我想它通过POST发送。什么是正确的方法来实现这样的事情?我需要使用什么课?我可以使用 HttpPost 这个例子的?如果是的话,我将如何构建 InputStreamEntity 我的位图?我会觉得令人作呕到需要先存储该位图中的设备上的文件。

Now, let's say that I generate a bitmap like so: Bitmap image = this.getBitmap() inside a control derived from View and I want to send it via POST. What would be the proper procedure to achieve such a thing? What classes do I need to use? Can I use HttpPost like in this example? If so, how would I construct the InputStreamEntity for my bitmap? I would find it revolting to be required to first store the bitmap in a file on the device.

我还要提到的是我真的需要发送的原始位图到服务器的每一个不变的像素,所以我不能将它转换为JPEG格式。

I should also mention that I really need to send every unaltered pixel of the original bitmap to the server, so I can't convert it to JPEG.

推荐答案

我不知道为什么的HttpURLConnection 类不提供发送文件,而无需编写任何手段手动档包装。下面是我落得这样做,但如果有人知道一个更好的解决方案,请让我知道。

I have no idea why the HttpURLConnection class does not provide any means to send files without having to compose the file wrapper manually. Here's what I ended up doing, but if someone knows a better solution, please let me know.

输入数据:

Bitmap bitmap = myView.getBitmap();

静态的东西:

Static stuff:

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);

开始的内容包装:

Start content wrapper:

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);

转换位图的ByteBuffer

//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);

结束内容包装:

End content wrapper:

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

刷新输出缓冲:

Flush output buffer:

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();

关闭响应流:

Close response stream:

responseStream.close();

关闭连接:

httpUrlConnection.disconnect();

PS:当然,我不得不换行私有类AsyncUploadBitmaps请求延伸AsyncTask的&LT;位图,太虚,字符串&GT; ,为了使Android平台幸福的,因为它不喜欢有主线程上的网络请求。

PS: Of course I had to wrap the request in private class AsyncUploadBitmaps extends AsyncTask<Bitmap, Void, String>, in order to make the Android platform happy, because it doesn't like to have network requests on the main thread.

这篇关于发送使用POST文件的HttpURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆