글
Volley를 이용하여 간단한 HTTP 통신을 하는 예제이다.
1. AndroidManifest.xml 에서 권한 명시
<uses-permission android:name="android.permission.INTERNET" />
2. build.gradle 내 dependencies 에 Volley 사용을 위한 명시
compile 'com.android.volley:volley:1.1.0'
3. Build - Make Project 를 하여 프로젝트에서 Volley 사용 가능
4. HTTP 통신 예제
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log.i
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var request: RequestQueue
lateinit var stringRequest: StringRequest
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setup RequestQueue
request = Volley.newRequestQueue(this)
val url = "http://www.google.com"
// Setup StringRequest
stringRequest = StringRequest(Request.Method.GET, url, Response.Listener<String> {
response -> textView1.text = response // Print http source using textview
}, Response.ErrorListener {
error -> i(applicationContext.packageName, error.toString()) // Print log if error occurred
})
// Set tag for cancel
stringRequest.tag = applicationContext.packageName
// Request
request.add(stringRequest)
}
override fun onStop() {
super.onStop()
// Cancel all request that have packageName tag
if(request != null) {
request.cancelAll(applicationContext.packageName)
}
}
}
GitHub : https://github.com/Hot6ix/SimpleHttpRequest
출처 : https://developer.android.com/training/volley/simple.html
'Android > Kotlin' 카테고리의 다른 글
Constraint Layout을 이용한 Floating action button Menu 만들기 (0) | 2018.01.09 |
---|---|
커스텀 리스트뷰 ( Custom ListView) (0) | 2017.12.21 |
RECENT COMMENT