0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Androidアプリ(Java)からAPIでJSONをGETしてログに表示する方法

Posted at

やりたいこと

Android StudioにてJavaで実装中のアプリからAPIを呼び出して、
返ってきたJSONレスポンスをデコードして、データ(文字列)を取り出す。
取り出した値を、Android StudioのLogcatに表示する。

前提

  • APIが実装済みで、ローカル開発環境の仮想サーバなどで稼働中であること。
  • APIがHTTP(sではなく)でアクセス可能であり、JSONレスポンスを返すこと。

APIレスポンス

下記のようなJSONが返るとする。

{"name":"yamato","age":42}

Android StudioでのJava実装

1. HTTP通信を許可する。

resの下にxmlディレクトリを作成し、下記のファイルを作成する。

res/xml/network_security_config.xml

内容は下記のように記述する。ここで「192.168.1.8」は、APIサーバのIPアドレスとする。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.1.8</domain>
    </domain-config>
</network-security-config>

続いて、
AndroidManifest.xml
を編集し、下記のように

<uses-permission android:name="android.permission.INTERNET" />

android:networkSecurityConfig="@xml/network_security_config"

を追記する。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yamato">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

2. Gradleにimplementationを追加する。

Gradleスクリプト/build.gradle(モジュール:app)に

    implementation 'com.squareup.okhttp3:okhttp:4.0.0-alpha02'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.3.4'

を追記する。dependenciesが下記のようになる。

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.squareup.okhttp3:okhttp:4.0.0-alpha02'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.3.4'
}

3. APIクライアントを実装する。

下記のようなクラスを作成する。

package com.example.yamato;

import android.util.Log;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ApiClient {
    void doGetRequest(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(final Call call, IOException e) {
                        String msg = e.getMessage();
                        Log.d("onFailure","msg:" + msg);
                    }
                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        String jsonText = response.body().string();
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode node = mapper.readTree(jsonText);
                        String name = node.get("name").asText();
                        String age = node.get("age").asText();
                        Log.d("name","" + name);
                        Log.d("age","" + age);
                    }
                });
    }
}

4. APIを呼び出す。

たとえば
MainActivity.java
などから、下記のように呼び出す。
ID:btnのビュー(ボタン)クリック時にAPIが呼ばれるようにする。

        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(
                new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        ApiClient apiClient = new ApiClient();
                        String api_url = "http://192.168.1.8/api/contents";
                        try {
                            apiClient.doGetRequest(api_url);
                        } catch (IOException e) {

                        }
                    }
                }
        );

5. 結果を確認する。

btn(ボタン)をクリックしてAPIが非同期で呼ばれ、
Logcatに

name: yamato
age: 42

が表示されたらOK。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?