我有访问API的代码,该API返回一系列测绘自行车路线的地理位置。这样,我首先获取JSON对象,然后将其转换为可绘制的点。对于与此API相关的所有异常,我都有一个APIGenericException,如果对API的请求失败,我想抛出APiRequestException(这是APIGenericException的子类)。我无法弄清楚如何抛出该异常,因为Volley的onErrorResponse()方法不会抛出异常。除此之外,convertResponseToWayPoints还会引发异常,但是我不确定如何将其传递给onResponse并传递给requestRouteFromAPI方法。
public void requestRouteFromAPI(Context mainActivityContext, final String url) throws APIGenericException {
RequestQueue queue = Volley.newRequestQueue(mainActivityContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
convertResponseToWayPoints(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error){
// TODO: Handle error
Log.e("ERROR", "Error occurred ", error);
throw new APiRequestException(url);
}
}); queue.add(jsonObjectRequest);}
我认为我可能有解决方案,但由于不了解Volley的请求如何运作,因此我不确定100%。如果请求是同步的,这是解决问题的一种方法吗?通过添加已分配的JSONObject,然后在方法之外进行处理。
private JSONObject APIrequestResponse;
public void getRoute(Context mainActivityContext) throws CycleStreetsException {
requestRouteFromCycleStreets(mainActivityContext, getAPIURL());
if(APIrequestResponse == null){
throw new CycleStreetsRequestException(getAPIURL());
}
else{
//make routes
}
}
public void requestRouteFromAPI(Context mainActivityContext, final String url) throws APIGenericException {
RequestQueue queue = Volley.newRequestQueue(mainActivityContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
APIrequestResponse = response;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error){
// TODO: Handle error
Log.e("ERROR", "Error occurred ", error);
APIrequestResponse = null;
}
}); queue.add(jsonObjectRequest);}