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.
Some preparation before implementation.
Add the following to AndroidManifest.xml. It's natural, but sometimes it's too natural to forget.
<uses-permission android:name="android.permission.INTERNET" />
Apparently, communication other than https from Android 9.x will result in an error. I get the following error.
java.io.IOException: Cleartext HTTP traffic to hoge.com not permitted
hoge.com is the domain or subdomain you want to access.
A configuration file is required to allow it. It's troublesome, but it corresponds.
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).
app/res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">www.bluecode.jp</domain>
</domain-config>
</network-security-config>
Specify the specified configuration file in AndroidManifest.xml.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jp.bluecode.http01">
<application
+ android:networkSecurityConfig="@xml/network_security_config"
android:allowBackup="true"
...
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.
MainActivity.java
MainActivity.java
package jp.bluecode.http01;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
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 java.io.IOException;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Widget initialization
txt01 = findViewById(R.id.txt01);
btn01 = findViewById(R.id.btn01);
//Button click
btn01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//http request
try{
//Custom function using okhttp (below)
httpRequest("http://www.bluecode.jp/test/api.php");
}catch(Exception e){
Log.e("Hoge",e.getMessage());
}
}
});
}
void httpRequest(String url) throws IOException{
//OkHttpClinet generation
OkHttpClient client = new OkHttpClient();
//request generation
Request request = new Request.Builder()
.url(url)
.build();
//Asynchronous request
client.newCall(request)
.enqueue(new Callback() {
//In case of error
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e("Hoge",e.getMessage());
}
//When normal
@Override
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
try{
//json purse
JSONObject json = new JSONObject(jsonStr);
final String status = json.getString("status");
//Parent thread UI update
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
@Override
public void run() {
txt01.setText(status);
}
});
}catch(Exception e){
Log.e("Hoge",e.getMessage());
}
}
});
}
}
activity_main.xml
I feel that you can implement the layout as you like, but for reference only.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/txt01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:text="Hello World!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txt01" />
</android.support.constraint.ConstraintLayout>
Recommended Posts