【问题标题】:Send json data from client to server using volley library使用 volley 库将 json 数据从客户端发送到服务器
【发布时间】:2015-05-30 08:40:33
【问题描述】:

我想从客户端向服务器发送一条简单的消息(服务器不是本地主机)。我使用 Volley 库和 POST 方法。 当我运行代码没有建立连接时,LogCat 打印:

05-30 12:19:05.930: D/memalloc(12085): /dev/pmem: Mapped buffer base:0x51dec000 size:3727360 offset:3112960 fd:48 
05-30 12:19:06.340: D/memalloc(12085): /dev/pmem: Mapped buffer base:0x5227a000 size:4382720 offset:3768320 fd:47
05-30 12:19:06.370: E/Volley(12085): [1] 2.onErrorResponse: Error:

客户端代码:

String url = "http://myWebServer.eu";
RequestQueue queue;
JsonObjectRequest request;
Map<String, String> map = new HashMap<String, String>();

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    queue = Volley.newRequestQueue(this);

    map.put("param1", "example");

    request = new JsonObjectRequest(Request.Method.POST, 

            url, 
            new JSONObject(map), 
            new Response.Listener<JSONObject>() { 
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        VolleyLog.v("Response:%n %s", response.toString(7));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() { 
                @Override
                public void onErrorResponse(VolleyError error) {

                    VolleyLog.e("Error: ", error.getMessage());
                }
            });

    queue.add(request);
}

PHP 服务器代码

$jsondata = $_POST['param1'];

$json = json_decode($jsondata,true);

echo $json ;

【问题讨论】:

  • 您是否在 Manifest 文件中设置了 Internet 权限?

标签: android json client server android-volley


【解决方案1】:

这里你尝试将非 json 类型解码为 json。 $post['param1'] 是字符串值,您可以从应用程序请求到服务器只需打印 $post['param1'] 是字符串格式而不是 json

$jsondata = $_POST['param1'];

echo $json_encode($_POST)  ;

【讨论】:

  • @ADamian 你能在这里发布你的logcat吗
  • 我认为问题是我们从服务器发送的响应不是 json 数据,并且在 app volley 库中尝试将数据转换为 json 对象
  • 在我的代码中,当我创建新请求时,我会创建一个新的 jsonobject。 “new JSONObject(map)”和map是php代码的参数。
  • volley JsonObjectRequest 仅支持响应中的 json 对象不接受此请求简单字符串或响应中不是 json 数组
【解决方案2】:

在你的php端写下代码:

$value = json_decode(file_get_contents('php://input'));
$json = $value->param1;

您还应该将 json 格式的响应发送回您的应用程序,正如您在这一行中看到的那样 (public void onResponse(JSONObject response))

还可以在您的帖子中添加标题:

@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put( "charset", "utf-8");
            return headers;
        }

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 2021-12-07
    • 2023-03-08
    • 1970-01-01
    • 2013-11-16
    • 2012-08-29
    • 2020-08-17
    • 2021-01-26
    • 1970-01-01
    相关资源
    最近更新 更多