- blog
- LoRaWAN on RAK3172 thanks to ST CubeMX, with VS Code
- Share this post
- Android — Send an HTTP(S) POST request
- BlocNotes
- Recent Posts
- Reverse engineer a wireless temperature sensor — Rika pellet stove
- LoRaWAN on RAK3172 thanks to ST CubeMX, with VS Code
- How to Execute HTTP POST Requests in Android
- Creating a Try Block and HttpURLConnection Object
- Posting the Output Request and Handling Exceptions
- Community Q&A
blog
LoRaWAN on RAK3172 thanks to ST CubeMX, with VS Code
Share this post
Android — Send an HTTP(S) POST request
As a part of my ioPush Android application, I needed to send a POST request to a secure server. I found some examples over the Internet but nothing parametric.
Here is my code, with optional basic HTTP authentication and headers.
Packages importation
// Required for httpPost() method import java.io.InputStream; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import android.util.Base64; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.net.HttpURLConnection; // Required for JSON handling import org.json.JSONException; import org.json.JSONObject;
POST request
private HttpResultHelper httpPost(String urlStr, String user, String password, String data, ArrayListString[]> headers, int timeOut) throws IOException // Set url URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // If secure connection if (urlStr.startsWith("https")) try SSLContext sc; sc = SSLContext.getInstance("TLS"); sc.init(null, null, new java.security.SecureRandom()); ((HttpsURLConnection)conn).setSSLSocketFactory(sc.getSocketFactory()); > catch (Exception e) Log.d(TAG, "Failed to construct SSL object", e); > > // Use this if you need basic authentication if ((user != null) && (password != null)) String userPass = user + ":" + password; String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT); conn.setRequestProperty("Authorization", basicAuth); > // Set Timeout and method conn.setReadTimeout(timeOut); conn.setConnectTimeout(timeOut); conn.setRequestMethod("POST"); conn.setDoOutput(true); if (headers != null) for (int i = 0; i headers.size(); i++) conn.setRequestProperty(headers.get(i)[0], headers.get(i)[1]); > > if (data != null) conn.setFixedLengthStreamingMode(data.getBytes().length); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(data); writer.flush(); writer.close(); os.close(); > InputStream inputStream = null; try inputStream = conn.getInputStream(); > catch(IOException exception) inputStream = conn.getErrorStream(); > HttpResultHelper result = new HttpResultHelper(); result.setStatusCode(conn.getResponseCode()); result.setResponse(inputStream); return result; >
How to call it
URL encoded with basic authentication
HttpResultHelper httpResult = httpPost("https://ioPush.net/app/api/getAuthToken", "**@ioPush.net", "**", null, null, 7000); BufferedReader in = new BufferedReader(new InputStreamReader(httpResult.getResponse())); String result = ""; String inputLine; while ((inputLine = in.readLine()) != null) result += inputLine; >
How to call it
JSON data with custom headers
String result = ""; String inputLine; // JSON data JSONObject data = new JSONObject(); try data.put("key1", "param1"); data.put("key2", param2); data.put("key3", "param3"); > catch (JSONException e) e.printStackTrace(); > // Headers ArrayListString[]> headers = new ArrayList<>(); headers.add(new String[]"custom-header", "custom value">); headers.add(new String[]"Content-Type", "application/json">); httpResult = httpPost("https://url.ext/page", null, null, data.toString(), headers, 7000); BufferedReader in = new BufferedReader(new InputStreamReader(httpResult.getResponse())); while ((inputLine = in.readLine()) != null) result += inputLine; >
HttpResultHelpers
Mandatory class to return status code and response .
import java.io.InputStream; public class HttpResultHelper private int statusCode; private InputStream response; public HttpResultHelper() > public int getStatusCode() return statusCode; > public void setStatusCode(int statusCode) this.statusCode = statusCode; > public InputStream getResponse() return response; > public void setResponse(InputStream response) this.response = response; > >
BlocNotes
Notepad of a tinker, maker, hacker or whatever you call it 🙂
Recent Posts
Reverse engineer a wireless temperature sensor — Rika pellet stove
LoRaWAN on RAK3172 thanks to ST CubeMX, with VS Code
How to Execute HTTP POST Requests in Android
This article was co-authored by wikiHow Staff. Our trained team of editors and researchers validate articles for accuracy and comprehensiveness. wikiHow’s Content Management Team carefully monitors the work from our editorial staff to ensure that each article is backed by trusted research and meets our high quality standards.
This article has been viewed 403,511 times.
HTTP Post is part of a deprecated HTTP classes like org.apache.http and AndroidHttpClient as of Android 5.1. [1] X Research source Migrate your code to the HttpURLConnection classes which includes Posting functionality. HTTP Post is used in Java to request that a specific web server receive and store data submitted within a request form. The data is submitted and stored in name-value pairs. Examples of pairs include: email-your email address; username-your username; and password-your password.
Creating a Try Block and HttpURLConnection Object
android:name="android.permission.INTERNET" />
try //enter statements that can cause exceptions >
URL url = new URL(“http://exampleurl.com/”); HttpURLConnection client = (HttpURLConnection) url.openConnection();
URL url = new URL(“http://exampleurl.com/”); HttpURLConnection client = null; try client = (HttpURLConnection) url.openConnection(); >
Posting the Output Request and Handling Exceptions
- The setRequestProperty() function is used as the Accept-Encoding request header to disable automatic decompression.
client.setRequestMethod(“POST”); client.setRequestProperty(“Key”,”Value”); client.setDoOutput(true);
OutputStream outputPost = new BufferedOutputStream(client.getOutputStream()); writeStream(outputPost); outputPost.flush(); outputPost.close();
client.setFixedLengthStreamingMode(outputPost.getBytes().length); client.setChunkedStreamingMode(0);
catch(MalformedURLException error) //Handles an incorrectly entered URL > catch(SocketTimeoutException error) //Handles URL access timeout. > catch (IOException error) //Handles input and output errors >
finally if(client != null) // Make sure the connection is not null. client.disconnect(); >
Community Q&A
This method seems to be just a sample of what you should do in this point. You need then to do your own implementation to write data to the OutputStream. You can find a simple samples on internet explaining how to write different types of data to an OutputStream.
Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow
The Android Manifest file presents the Android system with essential information about the app and is required for every app in its root directory. The INTERNET permission grants access to the API that opens the device’s network sockets.
Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow
I’m receiving errors that the symbol cannot be resolved for the URL and HttpURLConnection objects. What packages am I supposed to import?
Android Studio can be set to automatically import packages once the symbols are references or pasted into the code. You can also manually add in the packages by typing in and without the book ended arrow symbols. To set Android Studio to automatically import packages, Windows and Linux users must click on File>Settings>Edti>General>Auto Import>Java and Mac users must click on Android Studio>Preferences. Change «Insert imports on paste» to all and mark «Add unambiguous imports on the fly» then save your changes.
Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow