post http code example
Example 1: post with httpie
echo '{"example": "exampleData"}' | http POST https://addressToPost.com/post
// OR
http POST https://addressToPost.com/post example=exampleData
// Both work the same way
Example 2: http response methods
resource HTTP response method is made up of three
components:
Response Status Code ==> 200, 301, 404, 500
(these are the most common ones)
Response Header Fields ==> Date, Server, LastModified, Content-Type
Response Body ==> This is the data that comes
back to the client from the server.
Example 3: post request using http
private HttpResultHelper httpPost(String urlStr, String user, String password, String data, ArrayList<String[]> 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;
}