支持json上传,服务器返回json字符串后,进行解析
package com.android.volley.toolbox;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.Request.ResponseListener;
import com.android.volley.Response.ErrorListener;
import com.android.volley.toolbox.HttpHeaderParser;
import java.io.UnsupportedEncodingException;
public class GsonRequest extends Request<String> {
private static final String PROTOCOL_CONTENT_TYPE = String.format("application/json; charset=%s", new Object[]{"utf-8"});
private final ResponseListener mListener;响应数据回调,回传了响应字符串,以及下面的object,mClass,根据回传进行解析;
private final String mRequestBody;序列化后的json字符串
private boolean object;返回的具体数据是否为对象
private Class mClass;json字符串反序列化为对象字节码的类型
<span style="white-space:pre"> </span>
public GsonRequest(int method, String url, String requestBody, Class clazz, ResponseListener listener, ErrorListener errorListener, boolean object) {
super(method, url, errorListener);
this.mClass = clazz;
this.mListener = listener;
this.mRequestBody = requestBody;
this.object = object;
}
public GsonRequest(String url, String requestBody, Class clazz, ResponseListener listener, ErrorListener errorListener) {
this(url, requestBody, clazz, listener, errorListener, true);
}
public GsonRequest(String url, String requestBody, Class clazz, ResponseListener listener, ErrorListener errorListener, boolean object) {
this(1, url, requestBody, clazz, listener, errorListener, object);
}
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException var4) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
protected void deliverResponse(String response) {
this.mListener.onResponse(response, this.mClass, this.object);
}
/** @deprecated */
public String getPostBodyContentType() {
return this.getBodyContentType();
}
/** @deprecated */
public byte[] getPostBody() {
return this.getBody();
}
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
}
public byte[] getBody() {
try {
return this.mRequestBody == null?null:this.mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException var2) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", new Object[]{this.mRequestBody, "utf-8"});
return null;
}
}