How to Send POST Data in Android
In Android development, it is common to exchange data with remote servers. A common method of communication is through HTTP POST requests. This article will guide you through the process of sending POST data to a PHP script and displaying the result.
Android API Level Compatibility
The provided code sample works on Android 6.0 and above. For Android devices running versions prior to 6.0, an updated answer is provided.
Using AsyncTask
public class CallAPI extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String urlString = params[0]; String data = params[1]; 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()); } return null; } }
Using Apache Http Client (Outdated)
public void postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); } catch (Exception e) { // TODO Auto-generated catch block } }
Note: The Apache Http Client solution is outdated and only works on Android devices up to 5.1. For Android 6.0 and above, use the updated code sample provided in the first response.
The above is the detailed content of How to Send POST Data in Android Using AsyncTask and Older Methods?. For more information, please follow other related articles on the PHP Chinese website!