LoginSignup
5
4

More than 5 years have passed since last update.

AndroidでgooのPOSTAPIを利用する

Last updated at Posted at 2015-10-24

gooAPIで今日やること

gooラボ APIに公開されている形態素解析APIでjsonデータを取得するまでのコードをAndroidで実装します

準備

まず、自分のアプリケーションIDを取得しましょう。githubアカウントが必要となります。
gooラボAPI利用方法

コード

以下のようになります。例外処理はお好みで

MorphologicalAnalysis.java


    static final String GOO_URL = "https://labs.goo.ne.jp/api/morph";
    String ID  = "取得したID";
private void post(String sentence){

        URL url = null;

        try{
            url = new URL(GOO_URL);
            URLConnection connection =url.openConnection();
            connection.setDoOutput(true);

            //ヘッダ
            connection.setRequestProperty("Content-Type", "application/json");

            OutputStream os = connection.getOutputStream();

            //jsonの中身書く
            String postStr = "{\"app_id\": \"" + ID + "\",\"sentence\": \"" + sentence + "\"}";


            PrintStream ps = new PrintStream(os);
            ps.print(postStr); //データをPOSTする
            ps.close();

            InputStream is = connection.getInputStream(); //結果を取得
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            String s;
            while ((s = reader.readLine()) != null) {
                Log.d("OUTPUT",s); //結果を出力
            }
            reader.close();

        }catch (IOException e) {
            e.printStackTrace();
        }
    }

Androidで実際に実行するときはAsyncTaskで包みます

MorphologicalAnalysis.java
new AsyncTask<Void ,Void ,Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                post("京都はめちゃめちゃ楽しい");
                return null;
            }
        }.execute();

結果

上のような入力からは次のような結果が返ってきます

{"request_id":"labs.goo.ne.jp\t..\t0","word_list":[[["京都","名詞","キョウト"],["は","連用助詞","ハ"],["めちゃめちゃ","名詞","メチャメチャ"],["楽し","形容詞語幹","タノシ"],["い","形容詞接尾辞","イ"]]]}

最後に

APIを利用したアプリなどを公開するときはクレジットの表記などが必要となるようなので要件等確認しておきましょう
gooラボAPI利用方法

5
4
0

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
5
4