2012-01-25 26 views
3

HTTP POSTを使用してデータをサーバーに送信しようとしました。 サーバーは、$ _POST ['file']にバイナリデータが必要です。HTTP POSTによるバイナリデータとテキストデータの送信

 URL url = new URL("http://example.com"); 
     URLConnection connection = url.openConnection(); 
     connection.setDoOutput(true); 
     OutputStream outputStream = connection.getOutputStream(); 
     outputStream.write("file=".getBytes()); 

       //byte[] buffer contains the data 
      outputStream.write(buffer);   
     outputStream.close(); 

ストリームに書き込む正しい方法はありますか?バッファ以外の文字列( "file =")を処理する必要がありますか?

答えて

0

はい、POSTでテキストを書き込むには、 `OutputStream 'に書き込む必要があります。パラメータの場合

、あなたは(&で分離された)キーと値のペアの文字列を作成し、以下のようにOutputStreamでそのデータのバイト配列を作成する必要があります:

String parameterString = "file=" + parameters.get("file") + "&" + "other=" + parameter.get("other"); 
outputStream.write(parameterString.getBytes("UTF-8"); //Don't forget, HTTP protocol supports UTF-8 encoding. 
outputStream.flush(); 

ファイルを実行するにはURLConnectionでアップロードする(BalusCの記事を参照)How to use java.net.URLConnection to fire and handle HTTP requests?

+0

問題は、私はバイナリファイルの集中を送信する必要があります。私はそれを "file ="に追加することはできないと思う? – Non

+0

いいえ、更新された記事を参照してファイルのアップロード方法を確認してください。 –

2

データをBase64文字列(すべてのシステムとの互換性)に変換することをお勧めします。

string result = Convert.ToBase64String(Encoding.UTF8.GetBytes(utf8Text)); 
関連する問題