1. Volley를 사용하겠다고 build.gradle에 선언해준다(매니페스트에 인터넷 사용은 당연한것!)

dependencies {

    implementation 'com.android.volley:volley:1.1.1'
    /* 생략 */
}

 

2. RequestQueue를 한번만 생성하도록 싱글톤으로 만든다

(출처 : developer.android.com/training/volley/requestqueue?hl=ko)

public class MySingleton {
        private static MySingleton instance;
        private RequestQueue requestQueue;
        private ImageLoader imageLoader;
        private static Context ctx;

        private MySingleton(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 MySingleton getInstance(Context context) {
            if (instance == null) {
                instance = new MySingleton(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;
        }
    }

 

3. 사용하고 싶은 곳에서 호출한다

3-1. 이렇게 위에서 만든 싱글톤으로 사용하거나

RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
        getRequestQueue();

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // Display the first 500 characters of the response string.
            textView.setText("Response is: "+ response.substring(0,500));
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            textView.setText("That didn't work!");
        }
    });

    // Add the request to the RequestQueue.
    queue.add(stringRequest);

3-2. 그냥 바로 겟인스턴스해서 써도 된다

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // Display the first 500 characters of the response string.
            textView.setText("Response is: "+ response.substring(0,500));
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            textView.setText("That didn't work!");
        }
    });

    // Add the request to the RequestQueue.
    MySingleton.getInstance(this).addToRequestQueue(stringRequest);

 

4. 파라미터로 요청을 보내고 싶다면 getParmas를 사용해 Map에 담아 보내면 된다. StringRequest, POST에서만 된다. JsonRequest에서는 안됨.

StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // Display the first 500 characters of the response string.
            textView.setText("Response is: "+ response.substring(0,500));
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            textView.setText("That didn't work!");
        }
    }){
    	@Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("key", value);
                params.put("key", value);
                
                return params;
            }
    };

    // Add the request to the RequestQueue.
    queue.add(stringRequest);

 

5. json으로 받고싶다면 argument 하나가 중간에 추가된다.

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                
            }
        });
        
        queue.add(jsonObjectRequest);

 

 

자세한건 여기에 더 있다

https://developer.android.com/training/volley?hl=ko

+ Recent posts