preloader

Search on AEQ-WEB

AEQ-WEB | Blog

Android HTTP Request - Async Task

Android HTTP Request

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.

HTTP_Request.apk
Download
HTTP Request Code
Download

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 page was automatically translated and may contain errors
Share:
thumbnail
05.06.2018
Android Image Upload

On this page we show you how to send an image via an Android APP with HTTP-POST to a PHP server. The source code is available here.

Alex @ AEQ-WEB
thumbnail
07.06.2018
Android GSM/LTE Status

On this page we show you how to get the status of the mobile network with android. The source code and the APK file are available here

Alex @ AEQ-WEB