Home >Java >javaTutorial >How to Send POST Data to a PHP Script from Android?
How to Send POST Data in Android
For developers proficient in PHP, JavaScript, and other scripting languages but new to Java and Android, this guide provides a solution for sending POST data to a PHP script and displaying the result.
Updated Approach (Android 6.0 )
This updated solution leverages AsyncTask, which is recommended for background tasks in Android.
public class CallAPI extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String urlString = params[0]; // URL to call String data = params[1]; // Data to post try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); OutputStream 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()); } } }
Original Approach (Android 5.1 and Below)
For devices running Android 5.1 and below, Apache HttpClient can be used:
public void postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); try { HttpResponse response = httpclient.execute(httppost); } catch (Exception e) { // Handle exceptions } }
The above is the detailed content of How to Send POST Data to a PHP Script from Android?. For more information, please follow other related articles on the PHP Chinese website!