如何在 Android 中发送 POST 数据
在 Android 开发时,了解如何将 POST 数据发送到远程服务器至关重要。本文提供了有关如何使用已弃用的 AsyncTask 和更现代的方法来实现此目的的全面指南。
已弃用的 AsyncTask 方法
以下代码片段演示了如何使用 AsyncTask 发送 POST 数据class:
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()); } } }
Android 6.0 的更新方法
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 (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } }
以上是如何在 Android 中发送 POST 数据:AsyncTask 与现代方法?的详细内容。更多信息请关注PHP中文网其他相关文章!