티스토리 뷰

Mobile/Android

[Android] Volley lib

춘햄 2022. 4. 10. 11:08

웹서버에 요청하고 응답을 받을 때는 직전 포스팅과 같이 HttpURL Connection 객체를 사용할 수 있지만 요청과 응답에 필요한 코드의 양도 많으며 Handler와 Thread 를 사용하기 때문에 이에 대한 개념이 부족하면 다소 어려울 수 있다.

 

이런 문제를 해결하기 위해 사용하는 여러 라이브러리가 존재하는데, 그 중 가장 많이 사용되는 라이브러리는 Volley이다.

 

Volley는 Request 객체를 만들고 이 Request 객체를 Request Queue에 넣어주기만 하면 알아서 웹서버에 요청을 하고 응답을 받는 과정을 진행한다. 

 

이 모든 과정을 메인 스레드에서 처리하기 때문에 따로 스레드를 생성할 필요도 없고, 메인에 있는 객체를 다루기 위한 핸들러를 구성할 필요도 없다.

 

바로 한번 확인해보자.


◎build.gradle

// https://mvnrepository.com/artifact/com.android.volley/volley
implementation group: 'com.android.volley', name: 'volley', version: '1.2.1'

◎AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.samplerequest">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
            android:usesCleartextTraffic="true"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.SampleRequest">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

◎MainActivity.java

package com.example.samplerequest;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    EditText editText;
    TextView textView;

    static RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeRequest();
            }
        });

        // RequestQueue 객체 생성
        if(requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }

    public void makeRequest() {
        String url = editText.getText().toString();

        // 요청을 보내기 위한 StringRequest 객체 생성
        StringRequest request = new StringRequest(Request.Method.GET, url,
                // 응답을 받을 리스너 객체: 응답을 받았을 때 onResponse 메서드 자동 실행
               new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        println("응답 ->" + response);
                    }
                },
                // 에러가 발생했을 때 호출될 리스너 객체: 응답을 받았을 때 onErrorResponse 메서드 자동 실행
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        println("에러 ->" + error);
                    }
                }) {
            //POST 방식을 사용하면서 요청 파라미터를 전달하고자 한다면, 
            // getParams() 메서드에서 반환하는 HashMap 객체에 파라미터를 넣어준다.
            @Nullable
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return new HashMap<String, String>();
            }
        };
        //cache
        request.setShouldCache(false);
        
        // RequestQueue 의 add()메서드를 사용하여 요청 보냄
        requestQueue.add(request);
        println("요청 보냄");
    }

    public void println(String data) {
        textView.append(data + "\n");
    }
}

 

Comments