Android HTTP Request - Async Task

In this article we show how to start an HTTP request with Android. A PHP script is called on the server. This script shows the IP address of the client as well as the time from the server. To prevent the app from crashing, there is an exception handler. If an error occurs, it outputs a corresponding error code. The HTTP request is executed in a task so that the user interface is not affected by load times. If the server sends a response, the TextView will be updated. In our code example, we have also integrated a button that can run the task again.

This code example also works with HTTPS encryption. For this, simply rewrite the URL from HTTP to HTTPS. You can also use POST & GET parameters with this example to send parameters to the server.

MainActivity: The private classes are located in the MainActivity.java file:

private class HttpTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... strURLs) {
        URL url = null;
        HttpURLConnection conn = null;
        try {
            url = new URL(strURLs[0]);
            conn = (HttpURLConnection) url.openConnection();
            int responseCode = conn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = url.openStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
               return result.toString().replace("/N/", System.getProperty("line.separator"));
            } else {
                return "Fail (" + responseCode + ")";
            }
        } catch (IOException e) {
            return "Unable to connect";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        TextView view_result = (TextView) findViewById(R.id.textView);
        view_result.setText(result);
    }
}

onCreate: In the OnCreate void, the task will be executed with the following command:

new HttpTask().execute("http://testserver.aeq-web.com/android_http_request");

Manifest: In the manifest, the permission for the Internet access must be set:

<uses-permission android:name="android.permission.INTERNET">
Info: This article has been partially translated automatically and may contain errors.

You Might Also Like

Anzeige:

Social Media

Newsletter