HttpURLConnectionでPOSTを使用してファイルを送信する 質問する

HttpURLConnectionでPOSTを使用してファイルを送信する 質問する

Android開発者は推薦するこのクラスを使用するにはHttpURLConnection、ビットマップ「ファイル」(実際にはメモリ内のストリーム) を 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();
    }
}

AlertDialogshowDialog は(無効な URL の場合)を表示するだけです。

さて、次のようにビットマップを生成したとします。Bitmap image = this.getBitmap()コントロールから派生し、POSTで送信したいとしますView。これを実現するにはどのような手順が適切でしょうか。どのクラスを使用する必要がありますか。HttpPostこの例? もしそうなら、InputStreamEntityビットマップの をどのように構築すればよいでしょうか? 最初にビットマップをデバイス上のファイルに保存する必要があるのは不快だと思います。


また、元のビットマップの変更されていないすべてのピクセルをサーバーに送信する必要があるため、JPEG に変換できないことにも注意してください。

ベストアンサー1

クラスが、ファイル ラッパーを手動で作成せずにファイルを送信する手段を提供しない理由がわかりません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);

Bitmapに変換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);

エンドコンテンツラッパー:

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

private class AsyncUploadBitmaps extends AsyncTask<Bitmap, Void, String>PS: もちろん、Android プラットフォームではメイン スレッドでネットワーク リクエストが行われることを好まないため、Android プラットフォームを満足させるために、リクエストを でラップする必要がありました。

おすすめ記事