首页 >Java >java教程 >如何在Android中使用HttpURLConnection发送POST数据?

如何在Android中使用HttpURLConnection发送POST数据?

DDD
DDD原创
2024-12-25 10:14:12787浏览

How to Send POST Data in Android Using HttpURLConnection?

在 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
    }
}

参考:

  • https://developer.android.com/reference/java/net/HttpURLConnection.html
  • 如何使用NameValuePair使用POST向HttpURLConnection添加参数

以上是如何在Android中使用HttpURLConnection发送POST数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn