您可以为此使用 Volley。它快速、流畅且轻便。
在你的 build.gradle 文件中,添加这一行并编译:
implementation 'com.android.volley:volley:1.1.1'
制作一个网络单例
public class NetworkSingleton {
private static NetworkSingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context ctx;
private NetworkSingleton(Context context) {
ctx = context;
requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized NetworkSingleton getInstance(Context context) {
if (instance == null) {
instance = new NetworkSingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
发出字符串请求:
StringRequest stringRequest = new StringRequest(Request.Method.GET, "URL to fetch",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This is executed after successful response to URL
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//If error occurs
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Add a header to request");
return params;
}
};
NetworkSingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
阅读更多关于凌空抽射的信息:
https://developer.android.com/training/volley