Androidで画像とテキストを同時に送る「マルチパート送信」の練習をしています。
teratailやQiitaなどで情報を集め、自分なりに以下のようなソースを書いてみました。
…が、ちょっとあいまいなところもあるので、確認の意味も含めて質問をさせてください。
public class PhotoTextSender extends AsyncTask<String, String, Integer> { HttpURLConnection con; DataOutputStream dos; URL url; Integer res; String text = "あいうえお"; String breaks = "\r\n"; String hyphens = "--"; String boundary = "*****"; @Override protected Integer doInBackground(String... para) { // URLを取得 try { url = new URL(para[0]); } catch (MalformedURLException e) { e.printStackTrace(); } // 画像をバイト配列に ByteArrayOutputStream bos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos); try { // 通信の準備 con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(5000); con.setRequestMethod("POST"); con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); con.setRequestProperty("Accept-Charset", "UTF-8"); con.setUseCaches(false); con.setDoOutput(true); // 出力ストリームを生成 dos = new DataOutputStream( con.getOutputStream()); // 出力ストリームにファイルを書き込み dos.writeBytes(breaks + hyphens + boundary + breaks); dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename=\"upfile.jpg\"" + breaks + breaks); dos.write(bos.toByteArray()); dos.writeBytes(breaks + hyphens + boundary + hyphens + breaks); // 出力ストリームにテキストを書き込み dos.writeBytes(hyphens + boundary + breaks); dos.writeBytes("Content-Disposition: form-data; name=\"message\"" + breaks + breaks); // 文字化け対策 byte[] bytes = text.getBytes(); for(int i = 0 ; i < bytes.length; i++){ dos.writeByte(bytes[i]); } // 通信スタート con.connect(); // レスポンスを取得 res = con.getResponseCode(); // 出力を閉じる dos.close(); } catch (IOException e) { e.printStackTrace(); } finally { // 通信を閉じる con.disconnect(); } return res; } public void onPostExecute(Integer res) { // 処理結果 if(res == HttpURLConnection.HTTP_OK){ Toast.makeText(MainActivity.this, "送信に成功しました", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(MainActivity.this, "送信に失敗しました", Toast.LENGTH_LONG).show(); } } }
この中で、writeBytesを使っている個所は「文字列(リクエストヘッダ)を出力ストリームに書き込んでいるから」で、writeを使っている個所は「バイト配列(ファイル)を出力ストリームに書き込んでいるから」という認識で合っていますでしょうか。いろんなサイトを見ていると、リクエストヘッダにはwriteBytesを使い、ファイルデータにはwriteを使っていたので…
コピペプログラマーにならないよう、中身をしっかり理解したいと思います。
先輩方々、ご教授のほど、よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/21 05:33
2018/11/21 05:35
2018/11/21 05:51
2018/11/21 06:00
2018/11/21 06:06
2018/11/21 06:26