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.



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


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. Cleartext HTTP traffic to not permitted 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).


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

Specifying the configuration file

Specify the specified configuration file in AndroidManifest.xml.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

+       android:networkSecurityConfig="@xml/network_security_config"

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.


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.

package jp.bluecode.http01;

import android.os.Handler;
import android.os.Looper;
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 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;

    protected void onCreate(Bundle savedInstanceState) {

        //Widget initialization
        txt01 = findViewById(;
        btn01 = findViewById(;

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

                //http request
                    //Custom function using okhttp (below)
                }catch(Exception e){


    void httpRequest(String url) throws IOException{

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

        //request generation
        Request request = new Request.Builder()

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

                    //In case of error
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    //When normal
                    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
                            //json purse
                            JSONObject json = new JSONObject(jsonStr);
                            final String status = json.getString("status");

                            //Parent thread UI update
                            Handler mainHandler = new Handler(Looper.getMainLooper());
                   Runnable() {
                                public void run() {

                        }catch(Exception e){



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


<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""

        android:text="Hello World!"
        app:layout_constraintTop_toTopOf="parent" />

        app:layout_constraintTop_toBottomOf="@+id/txt01" />



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