Android 프로그래밍 2

본문 바로가기
사이트 내 전체검색


Android 프로그래밍 2
Android 프로그래밍 2

1. Http GET/POST Request

페이지 정보

작성자 관리자 댓글 0건 조회 2,981회 작성일 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")
        }
    }
}

댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.