HTTP通信(Java)
(ブログ記事の一覧は「こちら」)
HTTP通信は、主にWebブラウザでアクセスする、httpで始まるURLでインターネットにアクセスすることです。
JavaではHttpURLConnectionクラスというHTTP通信を簡単に行うことのできるクラスが用意されています。
ここでは、JavaでHTTP通信する方法と、HTTP通信で受け取ったJSONデータをパースする方法を学びましょう。
HTTP通信
下のURLにアクセスすると、以下のJSONデータが得られることを確認してください。 http://mjey.php.xdomain.jp/sa2/sample/json/sample1.php
{"user":{"id":"A1234567","name":"Taro Yamada"}}
上のURLを用いて、HTTP通信で受け取ったデータをコンソールに出力するサンプルプログラムを以下に示します。実際に実行させて動作を確認してください。
String strUrl = "http://mjey.php.xdomain.jp/sa2/sample/json/sample1.php"; HttpURLConnection connection = null; InputStream in = null; InputStreamReader inReader = null; BufferedReader br = null; try { URL url = new URL(strUrl); // Connectionを取得 connection = (HttpURLConnection) url.openConnection(); // リクエストのメソッドを指定 connection.setRequestMethod("GET"); // 通信開始 connection.connect(); // レスポンスコードを取得(200:成功) int iStatus = connection.getResponseCode(); if (iStatus == HttpURLConnection.HTTP_OK) { // データを取得(バイト型) in = connection.getInputStream(); // テキスト形式の取得 inReader = new InputStreamReader(in); br = new BufferedReader(inReader); // テキストを取得 String strLine; StringBuilder sbSentence = new StringBuilder(); // 1行ずつテキストを読み込む while ((strLine = br.readLine()) != null) { sbSentence.append(strLine); } // JSONデータ(後で、この部分を修正する) System.out.println(sbSentence.toString()); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (inReader != null) { inReader.close(); } if (in != null) { in.close(); } if (connection != null) { connection.disconnect(); } } catch (IOException e) { e.printStackTrace(); } }
JSONデータ形式を含む全ての文字列が取得できたことを確認してください。
次に、JSONデータをパースするプログラムに書き換える方法について確認しましょう。
JSONライブラリの登録
(前回の JSONデータの読み取り と同じ手順を行います。)
以下のリンクからJSONライブラリを取得します。
https://mvnrepository.com/artifact/org.json/json
リストの「Version」欄から最新のものをクリックします。移動したページで、表の「Files」にある「bundle」をクリックすると、「json-xxxxxxxx.jar」がダウンロードされます。
次に、下図のように、プロジェクト名を右クリックして、「ビルド・パス」→「外部アーカイブの追加」を選択して、「json-xxxxxxxx.jar」を登録します。
JSONデータの読み込み
例1
先ほどのサンプルプログラムのJSONデータについて、各キーの値を取得するためのプログラムです。先ほどのテキストファイルの読み込みのサンプルに追記します。
// JSONオブジェクトのインスタンス作成 JSONObject jsonObj = new JSONObject(sbSentence.toString()); // キー"user"の値(JSONオブジェクト)をパース JSONObject item = jsonObj.getJSONObject("user"); // 各キーの値を出力 System.out.println(item.get("id")); System.out.println(item.get("name"));
例2
配列を含むJSONデータについても試してみます。
下のURLにアクセスすると、以下のJSONデータが得られることを確認してください。 http://mjey.php.xdomain.jp/sa2/sample/json/sample2.php
{"users":[{"id":"A1234567","name":"Taro Yamada"},{"id":"B1234567","name":"Jiro Tanaka"},{"id":"C1234567","name":"Ichiro Suzuki"}]}
各キーの値を取得するためのプログラムです。例1の部分から書き換えます。
// JSONオブジェクトのインスタンス作成 JSONObject jsonObj = new JSONObject(sbSentence.toString()); // キー"users"の値(JSON配列オブジェクト)をパース JSONArray items = jsonObj.getJSONArray("users"); for (int i = 0; i < items.length(); i++) { // JSONオブジェクトをパース JSONObject item = items.getJSONObject(i); // 各キーの値を出力 System.out.println(item.get("id")); System.out.println(item.get("name")); }
課題
下のURLにアクセスして得られるJSONデータについて、キー"id", "name"の各値を出力するプログラムを作成してください。 http://mjey.php.xdomain.jp/sa2/sample/json/sample3.php
参考
今回のサンプルと課題で使用したURLについて、それぞれ以下のPHPプログラムを実行しています。
http://mjey.php.xdomain.jp/sa2/sample/json/sample1.php
<?php $id = "A1234567"; $name = "Taro Yamada"; $user = array("id" => $id, "name" => $name); $response = array("user" => $user); echo json_encode($response, JSON_UNESCAPED_UNICODE); ?>
http://mjey.php.xdomain.jp/sa2/sample/json/sample2.php
<?php $id = array("A1234567", "B1234567", "C1234567"); $name = array("Taro Yamada", "Jiro Tanaka", "Ichiro Suzuki"); $user0 = array("id" => $id[0], "name" => $name[0]); $user1 = array("id" => $id[1], "name" => $name[1]); $user2 = array("id" => $id[2], "name" => $name[2]); $users = array(0 => $user0, 1 => $user1, 2 => $user2); $response = array("users" => $users); echo json_encode($response, JSON_UNESCAPED_UNICODE); ?>
http://mjey.php.xdomain.jp/sa2/sample/json/sample3.php
<?php $id = "A1234567"; $name = "Taro Yamada"; $info = array("id" => $id, "name" => $name); $user = array("info" => $info); $response = array("user" => $user); echo json_encode($response, JSON_UNESCAPED_UNICODE); ?>