LoginSignup
15
24

More than 5 years have passed since last update.

AndroidでPOSTリクエストを送付する(HttpURLConnection利用)

Last updated at Posted at 2016-01-31

以前、GETリクエストの記事を書きましたが
POSTリクエストも追記します。

送付するJSON文字列イメージ

{
    "user":{
    "name": "post",
    "password": "password",
    "password_confirmation": "password"
    }
}

final String json =
  "{\"user\":{" +
  "\"name\":\"name1\","+
  "\"password\":\"password\","+
  "\"password_confirmation\":\"password\""+
  "}}";

try {

   String buffer = "";
   HttpURLConnection con = null;
   URL url = new URL("URL");
   con = (HttpURLConnection) url.openConnection();
   con.setRequestMethod("POST");
   con.setInstanceFollowRedirects(false);
   con.setRequestProperty("Accept-Language", "jp");
   con.setDoOutput(true);
   con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
   OutputStream os = con.getOutputStream();
   PrintStream ps = new PrintStream(os);
   ps.print(json);
   ps.close();

   BufferedReader reader =
   new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
   buffer = reader.readLine();

   JSONArray jsonArray = new JSONArray(buffer);
   for (int i = 0; i < jsonArray.length(); i++) {
       JSONObject jsonObject = jsonArray.getJSONObject(i);
       Log.d("HTTP REQ", jsonObject.getString("name"));
   }
   con.disconnect();
   } catch (MalformedURLException e) {
       e.printStackTrace();
   } catch (ProtocolException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
   } catch (Exception e) {
       e.printStackTrace();
   }
}

(参考)
JavaでHTTPリクエスト
http://www.magata.net/memo/index.php?Java%A4%C7HTTP%A5%EA%A5%AF%A5%A8%A5%B9%A5%C8

JavaでJSON文字列を扱うライブラリはたくさんありますが
それを入れるまでもない程度なので、文字列をJSONの書式にそって
作成してPOSTで投げています。

サーバサイドはrailsなんですが、JSONの書式に沿った文字列を
作るときちんと取得できません。。
たとえば、文字列の最外を角かっこにすると([])、うまく取得できない。
railsの動きを別途追ってみる予定です。

Java側では、JSON文字列に角かっこがないとnew JSONArray(文字列)で
JSONオブジェクトに変換失敗します。今はこれを基準にして統一しています。

(参考)
JavaScript Object Notation
https://ja.wikipedia.org/wiki/JavaScript_Object_Notation
今後、Javaの標準APIにJSONを扱う機能が追加されるようです。

15
24
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
24