안드로이드/개발코드

volley로 post request 코드

GTaeho 2022. 2. 16. 14:45

volley로 post 요청을 할 때는 아래와 같이 하기.

 

헤더는 getHeaders() 로 넣고 body 내용은 getParams() 로 넣으면 되기.

 

// Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "포스트 요청 넣을 http 서버";

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                response -> {
                    Log.d(tag, "Response is : " + response);
                }, error -> {
            Log.d(tag, "That didn't work!" + error.getMessage());
        }) {
            @Nullable
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("id", "1");
                params.put("name", "Jacky");
                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Accept", "text/plain");
                params.put("Accept-Charset", "utf-8");
                params.put("Accept-Language", "ko, en-US");
                params.put("Accept-Encoding", "br, gzip, deflate");
                params.put("Content-type", "application/x-www-form-urlencoded");
                return params;
            }
        };

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

 

 

build.gradle 의 dependencies에 

 

implementation 'com.android.volley:volley:1.2.1'

 

는 꼭 추가 해야한다.