Access Web API on Android with Get and process Json (Java for the time being)

Android has various options for Http communication and JSON processing, so it is hard for people who use it occasionally. .. .. OkHttp seems to be popular these days, so I'll try it.

Premise

specification

For the time being, if you press the button, you want to kick the Web API to get Json, parse it, and display it.

Install the program that returns the following Json on the server.

{"status":"OK","message":"Hello2019-05-31 07:06:23"}

The image below.

スクリーンショット 2019-05-31 7.08.57.png

Preparation

Some preparation before implementation.

Allow INTERNET access

Add the following to AndroidManifest.xml. It's natural, but sometimes it's too natural to forget.

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

Communication domain permission (non-https)

Apparently, communication other than https from Android 9.x will result in an error. I get the following error.

java.io.IOException: Cleartext HTTP traffic to hoge.com not permitted

hoge.com is the domain or subdomain you want to access.

A configuration file is required to allow it. It's troublesome, but it corresponds.

Installation of configuration file

Make the xml file with the following contents easy. It seems that the file name and location can be anywhere (because it will be explicitly specified in the next process).

app/res/xml/network_security_config.xml


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

Specifying the configuration file

Specify the specified configuration file in AndroidManifest.xml.

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.bluecode.http01">

    <application
+       android:networkSecurityConfig="@xml/network_security_config"
        android:allowBackup="true"
        ...

OkHttp settings

Add to Grandle's Module: app and Sync.

...
dependencies {
    ...
    implementation 'com.squareup.okhttp3:okhttp:4.0.0-alpha02'
}
...

That's all for preparation.

Implementation

Finally implemented. Communication processing etc. can not be done in the main thread for a long time. It is common sense to start in a separate thread and process asynchronously. OkHttp seems to be described as follows.

MainActivity.java

MainActivity.java


package jp.bluecode.http01;

import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    //Widget declaration
    TextView txt01;
    Button btn01;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Widget initialization
        txt01 = findViewById(R.id.txt01);
        btn01 = findViewById(R.id.btn01);

        //Button click
        btn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //http request
                try{
                    //Custom function using okhttp (below)
                    httpRequest("http://www.bluecode.jp/test/api.php");
                }catch(Exception e){
                    Log.e("Hoge",e.getMessage());
                }

            }
        });
    }

    void httpRequest(String url) throws IOException{

        //OkHttpClinet generation
        OkHttpClient client = new OkHttpClient();

        //request generation
        Request request = new Request.Builder()
                .url(url)
                .build();

        //Asynchronous request
        client.newCall(request)
                .enqueue(new Callback() {

                    //In case of error
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.e("Hoge",e.getMessage());
                    }

                    //When normal
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                        //response retrieval
                        final String jsonStr = response.body().string();
                        Log.d("Hoge","jsonStr=" + jsonStr);

                        //JSON processing
                        try{
                            //json purse
                            JSONObject json = new JSONObject(jsonStr);
                            final String status = json.getString("status");

                            //Parent thread UI update
                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    txt01.setText(status);
                                }
                            });


                        }catch(Exception e){
                            Log.e("Hoge",e.getMessage());
                        }

                    }
                });
    }
}

activity_main.xml

I feel that you can implement the layout as you like, but for reference only.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:text="Hello World!"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt01" />

</android.support.constraint.ConstraintLayout>

reference

Recommended Posts

Access Web API on Android with Get and process Json (Java for the time being)
For the time being, run the war file delivered in Java with Docker
[First Java] Make something that works with Intellij for the time being
Use Java external library for the time being
Run Dataflow, Java, streaming for the time being
[Java] Get and display the date 10 days later using the Time API added from Java 8.
Impressions and doubts about using java for the first time in Android Studio
[Deep Learning from scratch] in Java 1. For the time being, differentiation and partial differentiation
Learn for the first time java # 3 expressions and operators
Prepare the environment for java11 and javaFx with Ubuntu 18.4
Form and process file and String data at the same time with Spring Boot + Java
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Hello World with Ruby extension library for the time being
Now is the time to get started with the Stream API
[Memo] Run Node.js v4.4.5 on CentOS 4.9 / RHEL4 (i386) for the time being (gcc-4.8 and glibc2.11 on LinuxKernel 2.6.9)
Java14 came out, so I tried record for the time being
Install the memcached plugin on MySQL and access it from Java
Get the acceleration and bearing of the world coordinate system on Android
[Android] Get the date on Monday
Building a DLNA server on Ubuntu (just move for the time being)
Java12 came out, so I tried the switch expression for the time being
Wait for PostgreSQL to start with Docker and then start the WEB service
Beginners create web applications with Java and MySQL (adding at any time)
[Java] How to get the current date and time and specify the display format
Activity transition with JAVA class refactoring and instance experimented on Android side
Android development-WEB access (GET) Try to get data by communicating with the outside. ~
Creating an app and deploying it for the first time on heroku
Introduction to java for the first time # 2
[Java 7] Divide the Java list and execute the process
Learning for the first time java [Introduction]
[Java8] Search the directory and get the file
[Java] Get the date with the LocalDateTime class
Android development-WEB access (POST) Try to communicate with the outside and send data. ~
Monitor the Docker container and SystemD process on the same host with Zabbix on Ubuntu.
I want you to use Scala as Better Java for the time being
Enter from docker-compose up for the time being, and learn Docker while learning the basic design of Web server (Nginx) ①
Check the options set for the running Java process
[Android] Get the tapped position (coordinates) on the screen
ChatWork4j for using the ChatWork API in Java
[Java] Set the time from the browser with jsoup
JSON with Java and Jackson Part 2 XSS measures
Android Studio development for the first time (for beginners)
[Java] Get images with Google Custom Search API
Install Amazon Corretto (preview) for the time being
Compile and run Java on the command line
Docker Container Operations with Docker-Client API for Java
[Android development] Get an image from the server in Java and set it in ImageView! !!
Going back to the beginning and getting started with Java ① Data types and access modifiers
A memo to do for the time being when building CentOS 6 series with VirtualBox
Dreaming of easily creating a Web API for the DB of an existing Java system
[Android studio / Java] What you don't understand when you touch it for the first time