1,Volley 自定义请求,返回GsonRequest,进行封装解
-
创建GsonRequest继承Request
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import java.io.UnsupportedEncodingException;
public class GsonRequest<T> extends Request<T>{
private Class<T> clazz;
private Response.Listener<T> mListener;
public GsonRequest(String url,Class<T> clazz, Response.Listener<T> mListener,Response.ErrorListener listener) {
super(Method.GET, url, listener);
this.clazz = clazz;
this.mListener = mListener;
}
//仿照StringRespnose
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
//将json字符串解析为javabean
T t = new Gson().fromJson(parsed, clazz);
return Response.success(t, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
-
调用进行网络访问返回是Gson格式
queue = Volley.newRequestQueue(this); //进行初始化
//参数1 URL,参2 JAVAbean 参3 成功监听,参4 失败监听
GsonRequest<User> gsonRequest = new GsonRequest<>(Api.TEST, User.class, new Response.Listener<User>() {
@Override
public void onResponse(User response) {
text.setText(response.name);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(gsonRequest);