How to Send POST Data in Android
When developing for Android, it's essential to know how to send POST data to remote servers. This article provides a comprehensive guide on how to achieve this using both the deprecated AsyncTask and a more modern approach.
Deprecated AsyncTask Method
The following code snippet demonstrates how to send POST data using the AsyncTask class:
public class CallAPI extends AsyncTask{ 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()); } } }
Updated Method for Android 6.0
public void postData() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); try { ListnameValuePairs = new ArrayList (2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3