No img

Volley


구글 IO2013에서 공개한 안드로이드 앱 http 통신 라이브러리로 다른 안드로이드용 http 클라이언트 라이브러리가 제공하는 기능을 제공하면서도 용량이 작고 빠른 실행속도를 보인다.

 

실습

0. 준비 하기

- build.gradle dependencies에 volley 추가

implementation 'com.android.volley:volley:1.1.1'

 

1. 클래스 파일에 RequestQueue 설정

- RequestQueue는 작업이 이루어지는 스레드를 관리한다.

- Request는 response 원본 데이터를 파싱하고 Volley는 파싱 된 response를 다시 메인 스레드로 전달

object VolleyService{
	fun testVolley(context: Context, success: (Boolean) -> Unit){
        val testJson = ...
        val testRequest = ...
        
        Volley.newRequestQueue(context).add(testRequest)
   	}
}
req_bt.setOnClickListener{
	VolleyService.testVolley(this){ testSuccess ->
    	if(testSuccess){
        	//통신 성공
        }else{
        	//통신 실패
        }
    }
}

 

2. Volley 설정 함수 구체화

https://blog.yena.io/studynote/2017/12/12/Android-Kotlin-Volley.html

 

[Android][Kotlin] 안드로이드 코틀린 Volley

Volley 안드로이드의 Volley는 안드로이드 앱에서 쉽고 빠르게 네트워크 통신을 할 수 있게 해주는 HTTP 라이브러리이다. (한글로 적었는데, 다시 보니 모두 영어다) 기본적으로 안드로이드에서 Web Re

blog.yena.io

위 블로그 참고(Volley가 아닌 Retrofit을 사용할 예정이라...^^)

 

 

Retrofit


Square사에서 제공하는 HTTP REST API 구현을 위한 오픈소스 라이브러리로 REST API를 구현한 상태이므로 간단하게 GET, POST, PUT, DELETE 등을 전달하면 서버에서 처리 후 XML, JSON 등으로 응답을 제공받을 수 있는 형태다.

 

실습

0. 준비 하기 - build.gradle에 추가

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

 

+) https 통신이 기본이기 때문에 http도 허용해줬다. (manifest.xml)

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

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

 

1. Retrofit 초기화

var retrofitService: API

    init{
        val retrofit = Retrofit.Builder()
            .baseUrl("bonggang.tistory.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        retrofitService = retrofit.create(API::class.java)
    }

 

2. Retrofit 인터페이스 설정

interface API{
    @GET("/경로")
    fun func2() : Call<String>

    @FormUrlEncoded
    @POST("/경로")
    fun func1(@Field ("id") id:String, @Field("pw") pw:String) : Call<dataObject>
}

@GET, @POST, @PUT, @DELETED, @HEAD 등의 자료는 Retrofit API 문서를 참고

https://square.github.io/retrofit/

 

Retrofit

A type-safe HTTP client for Android and Java

square.github.io

 

3. 응답받은 데이터 처리

ClientNetActivity.retrofitService.func1("?","?").enqueue(object : Callback<dataObject>{
                override fun onResponse(call: Call<dataObject>, response: Response<dataObject>) {
                   Log.d("S", response.body().toString());
                }

                override fun onFailure(call: Call<dataObject>, t: Throwable) {
                    Log.d("F", t.toString())
                }
            })

 

 

참고 자료


https://cntechsystems.tistory.com/30

https://thdev.tech/androiddev/2016/11/13/Android-Retrofit-Intro/

https://square.github.io/retrofit/

https://gwi02379.tistory.com/3

https://zzdd1558.tistory.com/241