Home >Java >javaTutorial >How to Send POST Data in Android Using HttpURLConnection?
Sending POST Data in Android
POST requests are used to send data to a server in order to create or update a resource, typically in the form of a web form. In this case, the task is to send POST data to a PHP script on a server and display the results.
Solution (Updated for Android 6.0 ):
The recommended approach is to use the HttpURLConnection class. Here's a Java snippet demonstrating how to send POST data:
public class CallAPI extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String urlString = params[0]; String data = params[1]; 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()); } return null; } }
Original Solution (Outdated for Android 6.0 ):
Prior to Android 6.0, the Apache HttpClient library could be used for HTTP Post requests:
public void postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 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 } }
References:
The above is the detailed content of How to Send POST Data in Android Using HttpURLConnection?. For more information, please follow other related articles on the PHP Chinese website!