要在Android Volley中发送多个请求,可以使用Volley的RequestQueue和Request来管理多个请求。下面是一个示例代码:
public class MyRequestQueue {
private static MyRequestQueue instance;
private RequestQueue requestQueue;
private Context context;
private MyRequestQueue(Context context) {
this.context = context.getApplicationContext();
requestQueue = getRequestQueue();
}
public static synchronized MyRequestQueue getInstance(Context context) {
if (instance == null) {
instance = new MyRequestQueue(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
return requestQueue;
}
public void addToRequestQueue(Request request) {
getRequestQueue().add(request);
}
}
public class GetRequest extends Request {
private Response.Listener listener;
public GetRequest(String url, Response.Listener listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
String result = new String(response.data);
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
listener.onResponse(response);
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String URL1 = "http://example.com/api1";
private static final String URL2 = "http://example.com/api2";
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
// 发送第一个请求
MyRequestQueue.getInstance(this).addToRequestQueue(new GetRequest(URL1, new Response.Listener() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Response1: " + response);
textView.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error1: " + error.getMessage());
}
}));
// 发送第二个请求
MyRequestQueue.getInstance(this).addToRequestQueue(new GetRequest(URL2, new Response.Listener() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Response2: " + response);
// 处理第二个请求的响应
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error2: " + error.getMessage());
}
}));
}
}
注意: