How to Do an Https Post from Android

How to do an HTTPS POST from Android?

You can use the default CAs that are defined in the android device, which is just fine for any public web.

If you have a self-signed certificate, you can either accept all certificates (risky, open to man-in-the-middle attacks) or create your own TrustManagerFactory, which is a bit out of this scope.

Here's some code to use the default CAs for a https POST call:

private InputStream getInputStream(String urlStr, String user, String password) throws IOException
{
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

// Create the SSL connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());

// Use this if you need SSL authentication
String userpass = user + ":" + password;
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);

// set Timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true);

// Add any data you wish to post here

conn.connect();
return conn.getInputStream();
}

To read the response:

String result = new String();
InputStream is = getInputStream(urlStr, user, password);
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}

Sending POST data in Android

Note (Oct 2020): AsyncTask used in the following answer has been deprecated in Android API level 30. Please refer to Official documentation or this blog post for a more updated example

Updated (June 2017) Answer which works on Android 6.0+. Thanks to @Rohit Suthar, @Tamis Bolvari and @sudhiskr for the comments.

    public class CallAPI extends AsyncTask<String, String, String> {

public CallAPI(){
//set context variables if required
}

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String data = params[1]; //data to post
OutputStream out = null;

try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();

urlConnection.connect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

References:

  • https://developer.android.com/reference/java/net/HttpURLConnection.html
  • How to add parameters to HttpURLConnection using POST using NameValuePair

Original Answer (May 2010)

Note: This solution is outdated. It only works on Android devices up to 5.1. Android 6.0 and above do not include the Apache http client used in this answer.

Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

How to send http post request from Android?

I am using this code and working as well. Try this code.

public static String httpPostRequest(Context context, String url, String email) {
String response = "";
BufferedReader reader = null;
HttpURLConnection conn = null;
try {
LogUtils.d("RequestManager", url + " ");
LogUtils.e("data::", " " + data);
URL urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

data += "&" + URLEncoder.encode("Email", "UTF-8") + "="
+ URLEncoder.encode(email, "UTF-8");

wr.write(data);
wr.flush();

LogUtils.d("post response code", conn.getResponseCode() + " ");

int responseCode = conn.getResponseCode();

reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

response = sb.toString();
} catch (Exception e) {
e.printStackTrace();
LogUtils.d("Error", "error");
} finally {
try {
reader.close();
if (conn != null) {
conn.disconnect();
}
} catch (Exception ex) {
}
}
LogUtils.d("RESPONSE POST", response);
return response;
}

How to POST to an HTTPS Site in android

I have written a function for all POST/PUT/GET request to HTTPS server

a. You have to Self-signed certificate stuff to be handled. Please include that for sure.

b. You have to tell which type of content-Type to want to send to server.

c. Depending upon server configuration. What ever request you are sending to server check through POSTMAN or curl command to verify if is working, before working on Android request.

public String createConnection (String urlS, String methodInvoked,String patchBody, String postBody,String putBody){
URL url ;
BufferedReader br = null;
String toBeReturned="";
try {
url = new URL(urlS);

HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] myTrustedAnchors = new X509Certificate[0];
return myTrustedAnchors;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};

// Create an SSLContext that uses our TrustManager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);

HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setConnectTimeout(60000);
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setHostnameVerifier(hostnameVerifier);

if (patchBody != null ){
Log.i(TAG, " createConnection with PATH with body" );
connection.setRequestMethod("PATCH");
connection.setRequestProperty("data",patchBody);
connection.addRequestProperty("Content-Type", "application/json");
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(patchBody);
dStream.flush();
dStream.close();
}
if (methodInvoked.equalsIgnoreCase("PATCH") && patchBody == null ){
Log.i(TAG, " createConnection with PATH without body" );
connection.setRequestMethod("PATCH");
// connection.addRequestProperty("Content-Type", "application/json");
// connection.setDoOutput(true);
}
if (postBody != null){
Log.i(TAG, " createConnection with POST with body" );
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(postBody);
dStream.flush();
dStream.close();
}

if (methodInvoked.equalsIgnoreCase("POST") && postBody == null ){
Log.i(TAG, " createConnection with POST without body" );
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//connection.addRequestProperty("Content-Type", "application/json");
}

if (putBody != null){
Log.i(TAG, " createConnection with PUT with body" );
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.addRequestProperty("Content-Type", "application/json");
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(putBody);
dStream.flush();
dStream.close();
}

responseCode = connection.getResponseCode();
InputStream in= null;
if(responseCode >= HttpsURLConnection.HTTP_BAD_REQUEST)
{

in = connection.getErrorStream();
br = new BufferedReader( new InputStreamReader(connection.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
String toBeReturned_1 = sb.toString();
Log.i(TAG, " createConnetion error received " + responseCode + " " + toBeReturned_1) ;

}
else{

br = new BufferedReader( new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
toBeReturned = sb.toString();

}

} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
if (br!=null)
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
Log.i(TAG, " createConnetion finally returned" + toBeReturned );
return toBeReturned;
}

Android send https post request to the server without deprecated methods

To avoid using deprecated methods in API connectivity, think about using Retrofit. It's a third party library which makes HTTP communication much simpler.

When using Retrofit, you can create an interface of an API endpoint and the use it like a method. The rest of the HTTP request is managed by the library.

Here is the link to the Retrofit github homepage:
http://square.github.io/retrofit/

How to HTTPS post in Android

I hope it would help. This is the code i used and worked perfectly fine.

private HttpClient createHttpClient()
{
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);

SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

return new DefaultHttpClient(conMgr, params);
}

Then create an HttpClient like this: -

HttpClient httpClient = createHttpClient();

and use it with HttpPost.

Cheers!!

EDIT

And i did not used RestTemplate in my code. I made a simple post request. If you need more help just let me know. It seems like i recently have done something similar to what you are looking for.



Related Topics



Leave a reply



Submit