Sidewalk: The IoT network from Amazon
08.05.2024
Elektronik | Funk | Software
Der Technik-Blog
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">
On this page we show you how to make an HTTP request with android. This code also supports HTTPS and can transmit POST and GET parameters
read moreOn 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.
read moreAEQ-WEB © 2015-2024 All Right Reserved