在 Android 中发送 POST 数据
POST 请求用于将数据发送到服务器以创建或更新资源,通常在网页表单的形式。在本例中,任务是将 POST 数据发送到服务器上的 PHP 脚本并显示结果。
解决方案(针对 Android 6.0 更新):
推荐的方法是使用 HttpURLConnection 类。下面是演示如何发送 POST 数据的 Java 代码片段:
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; } }
原始解决方案(对于 Android 6.0 已过时):
在 Android 6.0 之前,Apache HttpClient 库可用于 HTTP Post请求:
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 } }
参考:
以上是如何在Android中使用HttpURLConnection发送POST数据?的详细内容。更多信息请关注PHP中文网其他相关文章!