开发中经常会用到使用POST方式传递JSON格式字符串给服务器。Volley默认的情况下是不支持JSONRequest这种方式的,可以通过重写来实现。
如下所示:
public class MyJsonObjectRequest extends JsonRequest<JSONObject> {
private String stringRequest;
private static final String PROTOCOL_CHARSET = "utf-8";
/**
* 这里的method必须是Method.POST,也就是必须带参数。
* 如果不想带参数,可以用JsonObjectRequest,给它构造参数传null。GET方式请求。
*
* @param stringRequest 格式应该是 "key1=value1&key2=value2"
*/
public MyJsonObjectRequest(String url, String stringRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Request.Method.POST, url, stringRequest, listener, errorListener);
this.stringRequest = stringRequest;
}
@Override
// public String getBodyContentType() {
// return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
// }
@Override
public String getBodyContentType() {
return "application/json; charset=" + getParamsEncoding();
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
具体的使用方法如下:
/**
*校验短信验证码
*/
public void validataSMSCode(String mobile ,String code,final ModelListener<JSONObject> listener){
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("mobile",mobile);
jsonObject.put("code",code);
} catch (JSONException e) {
e.printStackTrace();
}
myJsonObjectRequest = new MyJsonObjectRequest(get_user_account_update_url, jsonObject.toString(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
System.out.println("----onResponse---->" + response.toString());
listener.onSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
System.out.println("---onErrorResponse---->" + error.getMessage());
listener.onFail(0, error.getMessage());
}
});
myJsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mQueue.add(myJsonObjectRequest);
}