【问题标题】:How to get data from WebApi2 using android volley with Content-Type and params?如何使用带有 Content-Type 和参数的 android volley 从 WebApi2 获取数据?
【发布时间】:2017-03-01 06:26:48
【问题描述】:

如何使用 Android Volley 连接到服务器并从 WebApi2 以 JSON 或 XML 格式获取数据,并将 HTTP 标头 Content-Type 定义为 application/json接受作为应用程序/JSON

我有一个简单的方法,如 WebApi2 中的 HttpPost,如下所示:

    [HttpPost]
    public String GetData([FromBody]string data)
    {            
        return data;
    }

如您所见,我使用谷歌扩展高级 REST 客户端来测试该方法,它可以正常工作。

我设置了 HTTP 标头和参数,然后服务器响应就是我发送的内容。

现在我想使用 Android Volley 连接到服务器并通过设置 HTTP 标头和参数来获取数据,但它不起作用,我只是得到错误!

public void HttpPOSTRequestWithParameters() {

    try {
        RequestQueue queue = Volley.newRequestQueue(getContext());

        JSONObject params = new JSONObject();
        params.put("data", "Hello World");

        JsonObjectRequest postRequest = new JsonObjectRequest(
                Request.Method.POST,
                "http://localhost:15369/api/Test/GetData",
                params,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("Response", response.toString());
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("ERROR", "error => " + error.toString());  
                    }
                }
        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json");
                headers.put("Accept", "application/json");
                return headers;
            }
        };

        queue.add(postRequest);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

这是我得到的错误:

com.android.volley.ServerError

我搜索了整个互联网,但找不到任何可以帮助我解决此问题的答案。

提前致谢。

【问题讨论】:

    标签: android json model-view-controller asp.net-web-api android-volley


    【解决方案1】:

    试试这样 映射参数 = 新的 HashMap params.put("数据", "Hello World");

    然后在这里 Request.Method.POST,"http://localhost:15369/api/Test/GetData", 新的 JSONObject(参数)

    【讨论】:

    • params.put("Data", "Hello World");
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    相关资源
    最近更新 更多