実に基本的なところで申し訳ないのですが、AsyncTaskのPOST処理を書いていて疑問に思ったことがあったので質問させてください。以下はあるリファレンス本に記載されているPOST処理ですが、コメントの「ここから~ここまで」にあるInputStreamReaderの役割がわかりません。GET処理でこれが必要になるのはわかるのですが、POST処理の場合はどのような役割を果たしているのでしょうか。
@Override protected String doInBackground(String... params) { StringBuilder builder = new StringBuilder(); try { URL url = new URL(params[0]); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); con.setDoOutput(true); OutputStream os = con.getOutputStream(); PrintStream ps = new PrintStream(os); ps.print(params[1]); ps.close(); /* ここから */ BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "Shift-JIS")); String line; while ((line = reader.readLine()) != null){ builder.append(line); } /* ここまで */ } catch (IOException e) { e.printStackTrace(); } return builder.toString(); }
なお、上記のソースは以下のように記述しても動作します。ただ、やはりInputStreamReaderがないとPOST処理が行われません。
@Override protected String doInBackground(String... params) { try { URL url = new URL(params[0]); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); con.setDoOutput(true); OutputStream os = con.getOutputStream(); PrintStream ps = new PrintStream(os); ps.print(params[1]); ps.close(); /* ここから */ new InputStreamReader(con.getInputStream()); /* ここまで */ } catch (IOException e) { e.printStackTrace(); } return null; }
リファレンス本に書いてあるからと何となく使うのは気持ち悪いので、ちゃんと理解しておきたいと思います。本当に基本的な質問で申し訳ないのですが、AsyncTaskのPOST処理でInputStreamReaderの果たす役割を教えていただけないでしょうか。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/30 07:47