I made an Android application that GETs with HTTP

I am a beginner in Android application development who wrote this article the other day. Make a note of what you learned today.

Caution

This article was written by beginners to make a note of what they have learned. There is a high possibility that it deviates from the implementation method or common sense method, so please be careful when using it as a reference for implementation, or you should stop at your own risk.

What I learned today

-It seems that it is better to use HttpUrlConnection to send HTTP / GET requests from Android apps now-> reference )

-HTTP communication needs to be implemented asynchronously in Android apps. It is necessary to communicate with a thread different from the thread that runs the application itself.

-It is the main thread that messes with the UI of the application, and the main thread cannot be tampered with from another thread (the UI cannot be tampered with)-> There is a device

I'm stumbling in various ways, but study while coding step by step!

What this article does not explain

The destination to throw the request this time is PHP implemented by myself on the server I made, and it is a program that returns the result appropriately with json for an appropriate GET request. This article doesn't touch on that, nor does it describe its implementation. Let's write it separately.

What I made today

With such a UI, make a request with GET to the URI entered in the editText at the top, and when the result is obtained, write the response body in the editText below.

1.png

"Request URL" is just a TextView. Just put it. I thought I was writing this article now, but this is not a URL but a URI, but it doesn't matter which one

The gap between this and the button written as GET is editTextUrl. I will try to make a GET request for this URL (URI). The GET button is just a button. Execute the method with onClick. Below that, editTextResponse is a space to display the result obtained by the request. Next time, let's put out the header separately from the response body. Secretly, there is a small textViewTime at the bottom. Measure the time it took to get the request and try to output it.

So I wrote the following code.

MainActivity.java


package com.example.hogehogehoge.testapp11;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    TextView textViewUrl;
    EditText editTextUrl;
    Button buttonGet;
    EditText editTextResponse;
    TextView textViewTime;
    long startTime;
    long endTime;

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

        textViewUrl = (TextView)findViewById(R.id.textViewUrl);
        textViewTime = (TextView)findViewById(R.id.textViewTime);
        editTextUrl = (EditText)findViewById(R.id.editTextUrl);
        buttonGet = (Button)findViewById(R.id.buttonGet);
        textViewTime = (TextView)findViewById(R.id.textViewTime);
        editTextResponse = (EditText)findViewById(R.id.editTextResponse);

        editTextUrl.setText("http://My test server/get.php?target=test");
    }

    //For checking the operation of button click
    public void onButtonGetTest(View view) {
        Toast.makeText(this,"click test",Toast.LENGTH_SHORT).show();
    }

    public void onButtonGet(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(editTextUrl.getText().toString());
                    //Processing start time
                    startTime = System.currentTimeMillis();
                    HttpURLConnection con = (HttpURLConnection)url.openConnection();
                    final String str = InputStreamToString(con.getInputStream());
                    //Processing end time
                    endTime = System.currentTimeMillis();
                    Log.d("HTTP", str);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            editTextResponse.setText(String.valueOf(str));
                            textViewTime.setText("processing time:" + (endTime - startTime) + "ms");
                        }
                    });
                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }
        }).start();
    }

    // InputStream -> String
    static String InputStreamToString(InputStream is) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}

reference

HTTP communication (GET request) on Android Operate the UI of the main thread of the application from another thread

Commentary

When the app starts, onCreate is executed and in it


editTextUrl.setText("http://My test server/get.php?target=test");

Is executed and any URI is set in editTextUrl. Since it is editText, you can of course play with it yourself from the app.

When the GET button is pressed, the onButtonGet method defined in the onClick property is executed. Create a new thread, create a URL object in it, and execute HttpUrlConnection using the generated URL object. The obtained result is stored in str. If you do, use the InputStreamToString method you defined. (Refer to the reference page) In addition, the time is measured from the execution of this HttpUrlConnection to the point where the result is stored in str as the processing time (I wonder if it is okay here, in this case). Once, try to output the obtained result to the console using Log.d.

After that, call a convenient method called runOnUiThread that can operate the UI on the main thread, and set the obtained response and the measured time in the UI.

InputStreamToString method is sutra copying. Looking at the contents, it's like checking what's in Input (the contents of the response) line by line and continuing to append to the return value until it's empty. I can understand this somehow.

By the way

By the way, in this API, if you put test in the target query and request it, you will get the following response (json).

{"status":"true","res":"GET test success","explain":"GET test successed"}

There is no deep meaning. I just implemented it myself.

Execution result

Launch the app

2.png

Yup. As expected, it starts with an arbitrary (hard-coded in onCreate) URI inserted. When you press the GET button to execute it.

3.png

Probably because the processing time part became big, the result display part was misaligned to the right www

That's all for today (´ ・ ω ・ `)

Recommended Posts

I made an Android application that GETs with HTTP
Run an application made with Java8 with Java6
I tried to make an Android application with MVC now (Java)
I made a rock-paper-scissors app with android
I made an Android app for MiRm service
Run an application made with Go on Heroku
I made an iPhone Theremin with Vision framework + AudioKit
I want to push an app made with Rails 6 to GitHub
I made an adapter for communication class with Retrofit2 + Rx2
I made a mod that instantly calls a vehicle with Minecraft
I was addicted to WSl when trying to build an android application development environment with Vue.js
About creating an application with springboot
I tried to build an http2 development environment with Eclipse + Tomcat
I made an annotation in Java.
I made a matching app (Android app)
[Android] I made a pedometer app.
CentOS8 doesn't have unar binaries so I made an alternative with bash
I made an app to scribble with PencilKit on a PDF file
I made a site that summarizes information on carbohydrate restriction with Vue.js
I made a risky die with Ruby
I made a rock-paper-scissors app with kotlin
I made a calculator app on Android
Points I stumbled upon when creating an Android application [Updated from time to time]
The story of making an Android application that can adjust the sampling frequency of the accelerometer
04. I made a front end with SpringBoot + Thymeleaf
I made a mosaic art with Pokemon images
I made an app for myself! (Reading management app)
I made a gender selection column with enum
I made blackjack with Ruby (I tried using minitest)
I made an API client for Nature Remo
I tried to develop an application in 2 languages
Create an Annotator that uses kuromoji with NLP4J [007]
I made a portfolio with Ruby On Rails