[JAVA] OkHttp3 (GET, POST) in Android Studio

Use OkHttp3 to make GET and POST requests.

What I made

スクリーンショット 2019-04-24 18.50.21.png Place GET and POST buttons, and send each method request when the button is pressed.

MainActivity

MainActivity.java


package com.example.sampleapplication.sample.okhttp;

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

public class MainActivity extends AppCompatActivity {

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

        //Get GET button and POST button
        Button getButton = findViewById(R.id.getButton);
        Button postButton = findViewById(R.id.postButton);

        //When the GET button is tapped
        getButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpGet getTask = new OkHttpGet();
                getTask.execute();
            }
        });

        //When the POST button is pressed
        postButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpPost postTask = new OkHttpPost();
                postTask.execute();
            }

        });
    }
}

This time, I created separate classes for Get and Post, and called them. Each get.Task.execute(); postTask.execute(); I'm calling with.

GET

OkHttpGet.java


package com.example.sampleapplication.sample.okhttp;

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpGet extends AsyncTask<String,String,String> {
    @Override
    protected String doInBackground(String... strings) {

        // url
        String url = "GET request endpoint";
        //Response data
        String strData = "";

        //Instantiation of OkHttp
        OkHttpClient client = new OkHttpClient();

        //Build request including url
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try {
            //Request execution
            Response response = client.newCall(request).execute();
            //Get data from the body of the response
            strData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strData;
    }

    @Override
    protected void onPostExecute(String str) {
        Log.d("Debug",str);
    }
}

This time, I set the URL including the query in url. It seems that time-consuming processing cannot be executed in the main thread, so AsyncTask is used for asynchronous processing. Do a time-consuming process (here, a request using OkHttp) in doInBackground, and when it's done It feels like the process moves to onPostExecute. onPostExecute returns the result of asynchronous processing performed by doInBackground to the main thread. So if you want to display the result of the request on the screen, you can do it in this. Perhaps.

POST

OkHttpPost.java


package com.example.sampleapplication.sample.okhttp;

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPost extends AsyncTask<String,String,String> {

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    String json = "{\"name\":\"name\", \"taxis\":\"Classification\"}";

    @Override
    protected String doInBackground(String... strings) {

        OkHttpClient client = new OkHttpClient();

        String url = "URL used for POST";
        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String str) {
        Log.d("Debug",str);
    }
}

I am passing json format data by POST. Other than that, it is the same as GET.

Recommended Posts

OkHttp3 (GET, POST) in Android Studio
OkHttp (basic GET / POST)
Notes in Android studio
Automatically insert `@SuppressWarnings` in Android Studio
Get the result of POST in Java
Java to C and C to Java in Android Studio
How to use ExpandableListView in Android Studio
Riot (chat app) development (settings) in Android Studio
3 ways to import the library in Android Studio
Use the JDK used in Android Studio in the terminal
Get your version number in the Android app
Difficulties when implementing Alarm Manager in Android Studio
* Android * [HTTP communication_1] Try hitting WebAPI [GET, POST]
I got a cannot resolve symbol in Android Studio
Asynchronous processing and Web API integration in Android Studio
POST JSON in Java
Defeating Android Studio Part 3-6
Get cookies in Spring
Defeating Android Studio Part 1 & Part 2
Get Android location information
Refer to C ++ in the Android Studio module (Java / kotlin)
Use a JDK from another OpenJDK provider in Android Studio
How to get values in real time with TextWatcher (Android)
You are currently using Java 6. Solution in Android Studio Gradle
Get UserAgent in [Rails] controller
Get EXIF information in Java
[Java] Get KClass in Java [Kotlin]
Java in Visual Studio Code
[Android] Implement Adblock in WebView
POST Json in Java ~ HttpURLConnection ~
I tried to create a simple map app in Android Studio
The problem that XML attributes are sorted arbitrarily in Android Studio
Source to display character array with numberPicker in Android studio (Java)
[Android] I want to get the listener from the button in ListView
Determining if a custom keyboard is enabled in Android Studio (Java)