try {
RequestQueue jr = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
Log.d("The paramet ready", "Ready to go");
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
);
jr.add(jsonObject);
答案 0 :(得分:2)
我遇到了类似的问题。我有一个服务器API,返回一个JSON对象响应,所以JsonObjectRequest是go-to请求类型,但服务器不喜欢我的身体是JSON格式,所以我不得不对我的请求做一些更改。
这是我做的(适合您的代码):
JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("The response", response.toString());
progressDial.hide();
JSONArray json = null;
try {
json = response.getJSONArray("result");
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (json.getString(0).equalsIgnoreCase("0")) {
Log.d("JsonString: -> ", json.toString());
progressDial.hide();
toast();
} else {
startagain();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
progressDial.hide();
}
}
)
{
@Override
public byte[] getBody()
{
try
{
final String body = "&username=" + username + // assumes username is final and is url encoded.
"&password=" + password // assumes password is final and is url encoded.
return body.getBytes("utf-8");
}
catch (Exception ex) { }
return null;
}
@Override
public String getBodyContentType()
{
return "application/x-www-form-urlencoded";
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
在这里,我没有发送任何JSON对象作为帖子正文,而是我自己创建了帖子正文,形式为url编码。
我覆盖了以下方法:
答案 1 :(得分:0)
如果你的API返回一个JSON数组,那么你应该使用JsonArrayRequest,而不是JsonRequest。