I'm experienced with PHP, JavaScript and a lot of other scripting languages, but I don't have a lot of experience with Java or Android.
I'm looking for a way to send POST data to a PHP script and display the result.
HTTP POST requests supply additional data from the client (browser) to the server in the message body. In contrast, GET requests include all required data in the URL. Forms in HTML can use either method by specifying method="POST" or method="GET" (default) in the <form> element.
1) In case of Get request, only limited amount of data can be sent because data is sent in header. In case of post request, large amount of data can be sent because data is sent in body. 2) Get request is not secured because data is exposed in URL bar. Post request is secured because data is not exposed in URL bar.
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.
If you need to send a POST request with JSON data using Volley, you can do so with a JsonObjectRequest, and if you need to send or receive a JSON array in your POST request, you can use a JsonArrayRequest. First, you need to add the Volley library as a dependency of your project, as shown in the video below. Hire An Android Developer.
Most of the APIs post their data in JSON format. So we will also be posting our data to our API in the form of the JSON object. To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle (app) and add the below dependency in the dependencies section. After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
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:
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 } }
for Android = > 5
The org.apache.http classes and the AndroidHttpClient class have been deprecated in Android 5.1. These classes are no longer being maintained and you should migrate any app code using these APIs to the URLConnection classes as soon as possible.
https://developer.android.com/about/versions/android-5.1.html#http
Thought of sharing my code using HttpUrlConnection
public String performPostCall(String requestURL, HashMap<String, String> postDataParams) { URL url; String response = ""; try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode=conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line; } } else { response=""; } } catch (Exception e) { e.printStackTrace(); } return response; }
...
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{ StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); }
also you can Post method :
conn.setRequestMethod("POST");
Update 21/02/2016
for post request with json , see this example :
public class Empty extends AsyncTask<Void, Void, Boolean> { String urlString = "http://www.yoursite.com/"; private final String TAG = "post json example"; private Context context; private int advertisementId; public Empty(Context contex, int advertisementId) { this.context = contex; this.advertisementId = advertisementId; } @Override protected void onPreExecute() { Log.e(TAG, "1 - RequestVoteTask is about to start..."); } @Override protected Boolean doInBackground(Void... params) { boolean status = false; String response = ""; Log.e(TAG, "2 - pre Request to response..."); try { response = performPostCall(urlString, new HashMap<String, String>() { private static final long serialVersionUID = 1L; { put("Accept", "application/json"); put("Content-Type", "application/json"); } }); Log.e(TAG, "3 - give Response..."); Log.e(TAG, "4 " + response.toString()); } catch (Exception e) { // displayLoding(false); Log.e(TAG, "Error ..."); } Log.e(TAG, "5 - after Response..."); if (!response.equalsIgnoreCase("")) { try { Log.e(TAG, "6 - response !empty..."); // JSONObject jRoot = new JSONObject(response); JSONObject d = jRoot.getJSONObject("d"); int ResultType = d.getInt("ResultType"); Log.e("ResultType", ResultType + ""); if (ResultType == 1) { status = true; } } catch (JSONException e) { // displayLoding(false); // e.printStackTrace(); Log.e(TAG, "Error " + e.getMessage()); } finally { } } else { Log.e(TAG, "6 - response is empty..."); status = false; } return status; } @Override protected void onPostExecute(Boolean result) { // Log.e(TAG, "7 - onPostExecute ..."); if (result) { Log.e(TAG, "8 - Update UI ..."); // setUpdateUI(adv); } else { Log.e(TAG, "8 - Finish ..."); // displayLoding(false); // finish(); } } public String performPostCall(String requestURL, HashMap<String, String> postDataParams) { URL url; String response = ""; try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(context.getResources().getInteger( R.integer.maximum_timeout_to_server)); conn.setConnectTimeout(context.getResources().getInteger( R.integer.maximum_timeout_to_server)); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); Log.e(TAG, "11 - url : " + requestURL); /* * JSON */ JSONObject root = new JSONObject(); // String token = Static.getPrefsToken(context); root.put("securityInfo", Static.getSecurityInfo(context)); root.put("advertisementId", advertisementId); Log.e(TAG, "12 - root : " + root.toString()); String str = root.toString(); byte[] outputBytes = str.getBytes("UTF-8"); OutputStream os = conn.getOutputStream(); os.write(outputBytes); int responseCode = conn.getResponseCode(); Log.e(TAG, "13 - responseCode : " + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { Log.e(TAG, "14 - HTTP_OK"); String line; BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { Log.e(TAG, "14 - False - HTTP_OK"); response = ""; } } catch (Exception e) { e.printStackTrace(); } return response; } }
UPDATE 24/08/2016
Use some best library , such as :
because :
On lower API levels (mostly on Gingerbread and Froyo), HttpUrlConnection and HttpClient are far from being perfect
Since the introduction of Honeycomb (API 11), it's been mandatory to perform network operations on a separate thread, different from the main thread
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With