Summary of means when you want to communicate with HTTP on Android

** 2019/04/25 update ** I will summarize the means for HTTP communication on Android.

Due to server-side trends and changing programming paradigms, new and useful libraries will continue to emerge.

HttpUrlConnection (How to use Java standard URLConnection without using library)

https://developer.android.com/reference/java/net/HttpURLConnection.html

--With the retirement of Apache (Apache HttpClient, DefaultHttpClient, AndroidHttpClient), this is recommended as a low-level API. (Previously there was a bug)

Example

■ ** GET ** sample code with HttpUrlConnection

GET


    public static String get(String endpoint, String encoding, Map<String, String> headers) throws IOException {

        final int TIMEOUT_MILLIS = 0;//Timeout milliseconds: 0 is infinite

        final StringBuffer sb = new StringBuffer("");

        HttpURLConnection httpConn = null;
        BufferedReader br = null;
        InputStream is = null;
        InputStreamReader isr = null;

        try {
            URL url = new URL(endpoint);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setConnectTimeout(TIMEOUT_MILLIS);//Time to connect
            httpConn.setReadTimeout(TIMEOUT_MILLIS);//Time to read data
            httpConn.setRequestMethod("GET");//HTTP method
            httpConn.setUseCaches(false);//Use cache
            httpConn.setDoOutput(false);//Allow sending of request body(False for GET,Set to true for POST)
            httpConn.setDoInput(true);//Allow receiving body of response

            //Set HTTP header
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpConn.setRequestProperty(key, headers.get(key));//Set HTTP header
                }
            }
            httpConn.connect();

            final int responseCode = httpConn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                is = httpConn.getInputStream();
                isr = new InputStreamReader(is, encoding);
                br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
            } else {
                // If responseCode is not HTTP_OK
            }

        } catch (IOException e) {
            throw e;
        } finally {
            //fortify safe and Java1.6 compliant close processing
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
        return sb.toString();
    }

How to call GET


        //HTTP header(If you want to specify)
        Map<String,String> headers=new HashMap<String,String>();
        headers.put("X-Example-Header","Example-Value");
        String resultStr = get("http://hogehoge/foofoo", "UTF-8", headers);

■ ** POST ** with HttpUrlConnection (Example of POSTing JSON string)

POST


   public static String post(String endpoint, String encoding, Map<String, String> headers, String jsonString) throws IOException {

        final int TIMEOUT_MILLIS = 0;//Timeout milliseconds: 0 is infinite

        final StringBuffer sb = new StringBuffer("");

        HttpURLConnection httpConn = null;
        BufferedReader br = null;
        InputStream is = null;
        InputStreamReader isr = null;

        try {
            URL url = new URL(endpoint);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setConnectTimeout(TIMEOUT_MILLIS);//Time to connect
            httpConn.setReadTimeout(TIMEOUT_MILLIS);//Time to read data
            httpConn.setRequestMethod("POST");//HTTP method
            httpConn.setUseCaches(false);//Use cache
            httpConn.setDoOutput(true);//Allow sending of request body(False for GET,Set to true for POST)
            httpConn.setDoInput(true);//Allow receiving body of response

            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpConn.setRequestProperty(key, headers.get(key));//Set HTTP header
                }
            }

            OutputStream os = httpConn.getOutputStream();
            final boolean autoFlash = true;
            PrintStream ps = new PrintStream(os, autoFlash, encoding);
            ps.print(jsonString);
            ps.close();

            final int responseCode = httpConn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                is = httpConn.getInputStream();
                isr = new InputStreamReader(is, encoding);
                br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
            } else {
                // If responseCode is not HTTP_OK
            }

        } catch (IOException e) {
            throw e;
        } finally {
            //fortify safe and Java1.6 compliant close processing
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
        return sb.toString();
    }

How to call POST


        String postJson = "[{\"message\":{\"number\":\"1\",\"value\":\"Hello\"}}]";
        Map<String, String> headers = new HashMap<String, String>(); //HTTP header(If you want to specify)
        headers.put("X-Example-Header", "Example-Value");
        String postResult = post("http://hogehoge/foofoo", "UTF-8", headers, postJson);

Although it derails, java.net.HttpURLConnection of Android board has the same interface as the original JDK, but the Java implementation of Android is different from the original Oracle JDK (* 1), so it works with the Java runtime made by Oracle. Even so, it often didn't work on Android. (* 2)

(* 1) Android JDK has changed from Apache Harmony base to OpenJDK base. (* 2) If you bring the library tested with Pure Java (only) as it is, it will hurt.

Apache system (Apache HttpClient, DefaultHttpClient, AndroidHttpClient)

https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html?hl=ja#behavior-apache-http-client

--Deprecated in 5.1 and removed in 6.0 --Although there is a transitional measure, it is better not to use it anymore

volley https://developer.android.com/training/volley/index.html

--Various useful volleys for common Android scenes (asynchronous, etc.)

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

Excerpt from https://developer.android.com/training/volley/simple.html

OkHttp3 http://square.github.io/okhttp/ --Recently popular (apparently) --At the moment, the latest is OkHttp 3 series

maven/gradle https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

dependencies {
    compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.14.1'
}

Example

How to make REST operation (Request) with OkHttp3

GET

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

   public void doGet(String url) throws IOException {

        final Request request = new Request.Builder().url(url).build();
        final OkHttpClient client = new OkHttpClient.Builder().build();

        //Synchronous call
        Response response = client.newCall(request).execute();
        //View results
        System.out.println(response.body().string());
    }

POST

--If you want to Form POST

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

   public void doFormPost(String url) throws IOException {
        final FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("param_name", "param_value");

        final Request request = new Request.Builder()
                .url(url)
                .header("User-Agent", "Example client")
                .post(formBodyBuilder.build())
                .build();
        OkHttpClient client = new OkHttpClient.Builder()
                .build();
        //Synchronous call
        Response response = client.newCall(request).execute();
        //View results
        System.out.println(response.body().string());
    }

--If you want to POST the entire JSON

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

    public void doPost(String url, String jsonString) throws IOException {
        okhttp3.MediaType mediaTypeJson = okhttp3.MediaType.parse("application/json; charset=utf-8");

        RequestBody requestBody = RequestBody.create(mediaTypeJson, jsonString);

        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)//POST specification
                .build();
        OkHttpClient client = new OkHttpClient.Builder()
                .build();
        //Synchronous call
        Response response = client.newCall(request).execute();
        //View results
        System.out.println(response.body().string());
    }

PUT

final Builder formBodyBuilder = new FormBody.Builder();
	formBodyBuilder.add("param_name","param_value");
	
	final Request request = new Request.Builder()
			.url(url)
			.put(formBodyBuilder.build())
			.build();
	OkHttpClient client = new OkHttpClient.Builder()
                .build();
	Response response = client.newCall(request).execute();//Synchronous call

DELETE

	final Request request = new Request.Builder()
			.url(url)
			.delete()
			.build();
	OkHttpClient client = new OkHttpClient.Builder()
                .build();
	Response response = client.newCall(request).execute();//Synchronous call

** Synchronous call **

OkHttpClient client = new OkHttpClient.Builder()
				.build();
Response response = client.newCall(request).execute();

** Asynchronous call **

OkHttpClient client = new OkHttpClient.Builder()
				.build();

client.newCall(request).enqueue(new okhttp3.Callback() {

@Override
public void onResponse(Call call, Response response) throws IOException {

final String resString = response.body().string();
 //handler when updating view#post()To do
}

@Override
public void onFailure(Call call, IOException arg1) {

}
});

Retrofit2 http://square.github.io/retrofit/ --A library called "Leave it to REST!" By OkHttp developer. --REST operations (GET, POST, PUT, DELETE) can be realized with less description --Currently, the latest is Retrofit 2.x series

maven/gralde https://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit

Example

@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

(Excerpt from http://square.github.io/retrofit/)

Tools used with HTTP communication

JSON parser

I want to map JSON to a model class (POJO)

A site that automatically generates model classes corresponding to GSON and Jackson when using a JSON parser

Automatically generate model classes corresponding to GSON and Jackson from raw JSON and JSON Schema

http://www.jsonschema2pojo.org/

GSON https://mvnrepository.com/artifact/com.google.code.gson/gson

maven/gradle https://mvnrepository.com/artifact/com.google.code.gson/gson

Setting Example

build.gradle


 compile 'com.google.code.gson:gson:2.8.5'

Jackson https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

** (Bonus) Precautions when using Jackson as JSON Parser on Android **

compile 'com.fasterxml.jackson.core:jackson-databind:2.8.6'



 When building gradle, the JACKSON LICENSE file is duplicated and the following error message appears.

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE


 It is a good idea to write the following in the app level build.gradle.


#### **`build.gradle`**
```groovy

android {
Omission
 packagingOptions {

        exclude 'META-INF/LICENSE'

    }
}

The JSON operation is summarized in detail in ↓ Convert JSON to Java, Java to JSON-How to use GSON and Jackson-

Reactive programming

RxJava/RxAndroid https://mvnrepository.com/artifact/io.reactivex/rxandroid https://mvnrepository.com/artifact/io.reactivex/rxjava

Recommended Posts

Summary of means when you want to communicate with HTTP on Android
When you want to explicitly write OR or AND with ransack
When you want to change the MySQL password of docker-compose
docker-compose.yml when you want to keep mysql running with docker
lombok.config when you want to pass @Qualifier to @RequiredArgsConstructor with lombok
When you want to implement Java library testing in Spock with multi-module in Gradle in Android Studio 3
You can do anything with your Android smartphone or tablet! Summary of Arekore to move with Termux
A memo when you want to clear the time part of the calendar
The first thing to do when you want to be happy with Heroku on GitHub with Eclipse in Java
When you want to bind InputStream in JDBI3
Summary of moss when updating from JMockit 1.4 to 1.30
When you want to use the method outside
[Ruby] When you want to replace multiple characters
[java tool] A useful tool when you want to send the ipmsg log of PC-A to the specified PC on a regular basis.
Summary of copy and paste commands used when you want to delete the cache in iOS application development anyway
Summary of how to use the proxy set in IE when connecting with Java
Code to use when you want to process Json with only standard library in Java
If you want to use Mockito with Kotlin, use mockito-kotlin
[Android Studio] I want to use Maven library on Android
When you want to dynamically replace Annotation in Java8
I want to simplify the log output on Android
[Ruby + Rails] When you want to register in Mailchimp's mail list together with user registration
How to write in Model class when you want to save binary data in DB with PlayFramework
Use JLine when you want to handle keystrokes on the console character by character in Java
When you want to reflect the Master Branch information in the Current Branch you are currently working on
What to do when you launch an application with rails
Summary of initial work when creating an app with Rails
Delegate is convenient to use when you want to reuse parts
[Swift] When you want to know if the number of characters in a String matches a certain number ...
Comparison of version strings (Java implementation) when you want to branch the process between two versions
How to write when you want to handle "array of C language strings" like argv [] in Ruby-FFI
When you want to check whether the contents of a property can be converted to a specific type
A trick when you want to insert a lot of line breaks and tabs when substituting a character string
Problems with SDK apk JDK etc. that fail when building on Android with Unity. "Failed to build apk"
Results of trying to use NVENC (CUDA) with Ubuntu 18.04 on WSL2
I want to connect SONY headphones WH-1000XM4 with LDAC on ubuntu 20.04! !!
ProxyFactory is convenient when you want to test AOP in Spring!
I want to add a browsing function with ruby on rails
I want to avoid OutOfMemory when outputting large files with POI
When you want to ZIP download the image data saved locally
Summary of results of research on object orientation [Updated from time to time]
[Docker] Magic command when you want to wipe out none image
[Ruby on Rails] "|| =" ← Summary of how to use this assignment operator
How to write when installing Amazon Corretto 8 on CentOS 8 with Ansible.
When you have introduced devise but want to add more columns
How to call with One Touch (without confirmation) on Android (Java)
[Rails] I want to add data to Params when transitioning with link_to
Practice to use when you want to execute different processing groups serially
Summary of problems and countermeasures when operating IE with WebDriver of Selenium2
Summary of what we did to make JavaScript compatible with IE11
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]