Вы можете использовать залп для этого. Это быстро, плавно и легко.
В файле 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