我想向API发送请求并在Android中以JSON格式获取响应。我用Volley来帮助我。我打算在VolleyHelper中包装JsonObjectRequest,以便我更容易使用它。问题是JsonObjectRequest的onResponse()是void,所以我不能返回JSON对象。我的想法是让我的api调用很简单就像这样。
JSONObject response = VolleyHelper.getInstance(this).get(url);
JSONObject response = VolleyHelper.getInstance(this).post(url, params);
以下是Google建议的使用单例模式的帮助程序代码。
VolleyHelper
public class VolleyHelper {
private static VolleyHelper mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
public static synchronized VolleyHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleyHelper(context);
}
return mInstance;
}
private VolleyHelper(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
private <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public JSONObject get(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
//return jsonObject;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//return jsonerror
}
});
addToRequestQueue(request);
}
public JSONObject post(String url, Map<String, String> params) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
//return jsonObject;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//return jsonerror
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
addToRequestQueue(request);
}
}
答案 0 :(得分:0)
我不认为同步从异步操作返回任何内容是个好主意。 android中的整个异步层 - 无论是普通AsyncTask
还是Volley
- 是用另一种模式构建的 - &gt; callback
。在这种情况下的回调是在完成一个长期运行的&#34;网络任务。
所以,你应该设计你的助手类:
public interface OnFinishListener { public void onFinish( JSONObject o ); }
public class VolleyHelper {
public JSONObject get(String url, OnFinishListener ofl ) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
ofl.onFinish( jsonObject );
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//return jsonerror
}
});
addToRequestQueue(request);
}
}
然后:
OnFinishListener ofl = new OnFinishListener(){
@Override public void onFinish( JSONObject o ){
doSomethingOnJson( o );
}
}
JSONObject response = VolleyHelper.getInstance(this).get(url, ofl );
JSONObject response = VolleyHelper.getInstance(this).post(url, params, ofl );