使用Volley的JSON请求
问题描述:
我试图使用Volley发出JSON请求,我能够使用StringRequest成功发出请求,但是现在尝试执行JSONRequest时发生错误。使用Volley的JSON请求
private void postData(final String param, final TextView tv) {
RequestQueue request = Volley.newRequestQueue(this);
JsonObjectRequest postReq = new JsonObjectRequest(Request.Method.GET, url_login, new Response.Listener<JsonReader>() {
@Override
public void onResponse(JsonReader response) {
tv.setText(response); // We set the response data in the TextView
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error [" + error + "]");
}
}) {
/**
* Add the headers to the request
* @return headers
* @throws AuthFailureError
*/
@Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("customHeader", "someCrap");
System.out.println(headers); //testing output of headers
return headers;
}
};
request.add(postReq);
}
我在tv.setText(response)下得到一个错误;
无法解析法 '的setText(android.util.JsonReader)'
我想输出的JSON请求作为测试在TextView的文本标有 “电视”
谢谢你
答
TextView不接受JsonReader。你需要CharSequence或String。
有没有一种方法可以在设备上显示Json字符串?还是必须解析? – x10sion
我觉得你做的事很奇怪。为什么用JsonObjectRequest发起StringRequest?只要执行'StringRequest postReq = new StringRequest(...)'并用String替换'onResponse'中的JsonReader。 – inmyth
对不起,它应该是JsonObjectRequest postReq = new JsonObjectRequest(...)我已经改变了它的问题。关于你的建议,我想要做一个JSON请求作为一个XML(字符串)请求。我设法从发布Json的服务器获得成功的String请求,并且宁愿使用Json。我只是在努力通过响应来看到设备上的输出? – x10sion