HTTP:差异请求 属性 和 POST - 参数

HTTP: difference Request Property and POST - Parameters

我目前正在尝试使用 HttpURLConnection-class 通过 android 应用程序将 POST 方法发送到简单的 PHP 网络服务。多个教程使用缓冲编写器 class 将参数写入 http-body,但 HttpURLConnection 也有一个 setRequestProperty() 方法,它向连接添加一个键值对。显然它们不是用于相同的目的,但有什么区别(我也检查了 google,但没有找到答案)?

setRequestProperty()用于设置HTTP headers(类似Content-Type):

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

但要设置 POST 参数,您需要 url-encode 它们并将结果字符串(转换为字节流)写入从 HttpURLConnection 实例获得的 OutputStream

例如,要发送带有值 1a 和带有值 2b 作为 POST 参数,您可以执行以下操作:

final String urlEncodedString = "a=1&b=2";
final byte[] bytesToWrite = urlEncodedString.getBytes(StandardCharsets.UTF_8);
conn.getOutputStream().write(bytesToWrite);

这里,connHttpURLConnection的实例。

您使用过时的方式向服务器发出请求。 尝试使用一些库来减少许多不必要的代码,例如加载到缓冲区 reader 和转换过程,我建议您使用 volley 库,请阅读有关它的 google 文档。 您可以创建自定义 JSONObjectReuqest 并重写 getParams 方法,或者您可以在构造函数中将它们作为 JSONObject 提供以放入请求正文中。

像这样(我编辑了你的代码):

JSONObject obj = new JSONObject();
obj.put("key", "value");
obj.put("key2", "value2");
// add whatever you want

RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,SPHERE_URL,obj,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
             System.out.println(response);
             hideProgressDialog();
        }
    },
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
             hideProgressDialog();
        }
    });
queue.add(jsObjRequest);