【发布时间】: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