I am a beginner in Android application development who wrote this article the other day. Make a note of what you learned today.
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.
-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!
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.
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.
"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();
}
}
HTTP communication (GET request) on Android Operate the UI of the main thread of the application from another thread
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, 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.
Launch the app
Yup. As expected, it starts with an arbitrary (hard-coded in onCreate) URI inserted. When you press the GET button to execute it.
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