Http GET/POST Request > Android 프로그래밍 2

본문 바로가기

Android 프로그래밍 2

Android 프로그래밍 2

1. Http GET/POST Request

페이지 정보

작성자 관리자 댓글 0건 조회 4,780회 작성일 20-06-09 18:58

본문

1. Http GET/POST Request

Get Request

 

fun sendGetRequest(userName:String, password:String) {

    var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
    reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")

    val mURL = URL("<Yout API Link>?"+reqParam)

    with(mURL.openConnection() as HttpURLConnection) { //Or HttpsURLConnection
        // optional default is GET
        this.requestMethod = "GET"

        println("URL : $url")
        println("Response Code : $responseCode")

        BufferedReader(InputStreamReader(this.inputStream)).use {
            val response = StringBuffer()

            var inputLine = it.readLine()
            while (inputLine != null) {
                response.append(inputLine)
                inputLine = it.readLine()
            }
            it.close()
            println("Response : $response")
        }
    }
}


Post Request

 

fun sendPostRequest(userName:String, password:String) {

    var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
    reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")
    val mURL = URL("<Your API Link>")

    with(mURL.openConnection() as HttpURLConnection) { //Or HttpsURLConnection
        // optional default is GET
        this.requestMethod = "POST"

        val wr = OutputStreamWriter(this.outputStream)
        wr.write(reqParam)
        wr.flush()

        println("URL : $url")
        println("Response Code : $responseCode")

        BufferedReader(InputStreamReader(this.inputStream)).use {
            val response = StringBuffer()

            var inputLine = it.readLine()
            while (inputLine != null) {
                response.append(inputLine)
                inputLine = it.readLine()
            }
            it.close()
            println("Response : $response")
        }
    }
}


Copyright © LEELAB.CO.KR. All rights reserved.