** 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.
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.
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/)
I want to map JSON to a model class (POJO)
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-
RxJava/RxAndroid https://mvnrepository.com/artifact/io.reactivex/rxandroid https://mvnrepository.com/artifact/io.reactivex/rxjava
Recommended Posts