APP/안드로이드

안드로이드 volly사용

자코린이 2022. 2. 16. 01:14

안드로이드에서 JSON으로 외부 데이터를 가져오고 싶으면 간단히 volly를 사용하면 된다.

Volley를 사용하면 다음과 같은 이점이 있습니다.
  • 네트워크 요청의 자동 예약.
  • 여러 개의 동시 네트워크 연결
  • 표준 HTTP 캐시 일관성을 갖춘 투명한 디스크 및 메모리 응답 캐싱
  • 요청 우선순위 지정 지원
  • 취소 요청 API. 단일 요청을 취소하거나 취소할 요청의 블록 또는 범위를 설정할 수 있습니다.
  • 용이한 맞춤설정(예: 재시도, 백오프)
  • 강력한 정렬 기능을 이용하여 네트워크에서 비동기식으로 가져온 데이터로 UI를 올바로 채우는 작업을 쉽게 실행할 수 있음.
  • 디버깅 및 추적 도구.


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

volly를 사용하려면 요청 객체(Request)와 요청 큐(RequestQueue)를 만듭니다.

여기서 요청 객체를 요청 큐에 넣으면, 자동으로 큐가 서버에 요청을 하고 데이터를 받아옵니다.

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

volly를 사용하려면 build.gradle의 2번째 맨 아래쪽에 내용만 알맞게 넣어줍니다.(volly 설치)

dependencies {
        ...
        implementation 'com.android.volley:volley:1.1.1'
    }

그리고  맨 위의 manifests에 아래 내용을 넣어 줍니다.(<application>위에 넣어주세요)(인터넷 환경 허용)

<uses-permission android:name="android.permission.INTERNET"/>

마지막으로 http서버를 사용하면 아래 내용을 manifests에 넣어주세요(<application>안에 내용만 넣어주세요)(http 허용)

<application
    ...
    android:usesCleartextTraffic="true"
    >
</application>

여기까지 기본 환경설정이 끝났고, 객체와 큐를 만들어 봅시다.

 

기본적인 방법을 사용하겠습니다.

일단 AppHelper.java 라는 이름으로 자바 class를 만듭니다.

(MainActibity파일이 담긴 폴더에서 오른쪽 클릭을 사용해 생성할 수 있습니다.)

그 안에 아래 내용을 붙여넣습니다.(큐 생성 완료)

public class AppHelper {
    public static RequestQueue requestQueue;
}

 

이제 요청할 객체를 만들어 봅시다.

MainActivity에 아래 내용을 추가해 줍니다.

package kr.pe.jw.testapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

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

import javax.net.ssl.SSLHandshakeException;


public class MainActivity extends AppCompatActivity {
    EditText editText;
    TextView textView;

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

        editText = findViewById(R.id.editText); //아이디로 editText찾기
        textView = findViewById(R.id.textView); //아이디로 textView찾기

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() { // 버튼 클릭시 일어나는 이벤트
            @Override
            public void onClick(View v) {
                String url = editText.getText().toString(); //editText에 넣은 값을 문자열로 변환 후 변수에 정의
                sendRequest(url); // 함수 호출

            }
        });

        if(AppHelper.requestQueue == null) // 큐가 비어있으면 큐 생성
            AppHelper.requestQueue = Volley.newRequestQueue(getApplicationContext());

    }

    public void sendRequest(String url) {


        StringRequest request = new StringRequest(
                Request.Method.GET,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) { //데이터 성공적으로 받은 경우
                        textView.setText(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) { //데이터를 받는 과정에서 나온 에러 출력
                        textView.setText(error.getMessage());
                    }
                }
        ) {
            //post방식으로 받을 경우 사
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                //params.put("key", "value"용);
                return params;
            }
        };

        // 이전 결과가 있더라도 새로 요청
        request.setShouldCache(false);
        //초기화한 큐에 받아온 결과 추가
        AppHelper.requestQueue.add(request);
        AppHelper.requestQueue = Volley.newRequestQueue(this); // 큐 초기화 
        Toast.makeText(getApplicationContext(), "Request sent!!", Toast.LENGTH_SHORT).show();
    }
}

activity_main에 아래 내용을 추가 합니다.(내부 디자인)

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="url을 넣어주세요">

    </EditText>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="데이터 불러오기"
        android:textSize="40sp"
        android:id="@+id/button">

    </Button>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="300dp">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>

이제 빌드를 해서 결과를 확인하면, 잘 나오는 것을 알 수 있습니다.

하지만 애뮬레이터를 사용하면 안 돌아갑니다.

그 이유는 핸드폰의 시간이 홈페이지하고 달라 https인증서 인증에 실패하였기 때문입니다.

자세히 알고 싶다면 아래 페이지를 참고하세요

https://github.com/square/okhttp/issues/3180

 

javax.net.ssl.SSLHandshakeException: Chain validation failed · Issue #3180 · square/okhttp

This error occurs only in Android Nougat and above when use self-signed certificate。

github.com

 

 

 

참조 : https://recipes4dev.tistory.com/89?category=658689 

 

안드로이드 리니어레이아웃. (Android LinearLayout)

1. 안드로이드 LinearLayout 클래스 안드로이드에서 UI 화면을 구성할 때, View 위젯의 배치를 위한 컨테이너 역할을 하는 ViewGroup인 Layout 클래스는 그 종류가 매우 다양합니다. [안드로이드 레이아웃]

recipes4dev.tistory.com

https://ju-hy.tistory.com/66

 

Volley 라이브러리 사용법

Volley란? 앱에서 서버와 http 통신을 할 때 HttpURLConnection을 사용하면 직접 요청과 응답을 받는 것이 가능하다. 하지만 직접 쓰레드를 구현해야 하며, 기본적인 코드 양 또한 많아 코드가 복잡해진

ju-hy.tistory.com