안드로이드

안드로이드 kotlin : HttpURLConnection

제주도 조랑말 2024. 4. 17. 10:18
728x90

lat과 long은 보낼 데이터
서버에서 echo로 출력하면 logcat에 응답 출력

fun sendData(lat: Double, long: Double) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
        val url = URL(" 여기에 URL 입력하기 ") // 서버의 엔드포인트 URL로 변경하세요
        val postData = "lat=$lat&long=$long" // POST 데이터 포맷 설정

        // HttpURLConnection을 사용하여 서버에 HTTP POST 요청 보내기
        with(url.openConnection() as HttpURLConnection) {
            requestMethod = "POST" // 요청 메소드 설정
//            doOutput = true

            // 요청 헤더 설정
            setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
            setRequestProperty("Content-Length", postData.length.toString())

            // 데이터를 서버로 전송
            DataOutputStream(outputStream).use { it.writeBytes(postData) }

            // 서버 응답 읽기
            BufferedReader(InputStreamReader(inputStream)).use { reader ->
                val response = StringBuffer()
                var inputLine: String?
                while (reader.readLine().also { inputLine = it } != null) {
                    response.append(inputLine)
                }
                println("서버 응답: $response") // 서버 응답을 로그로 출력
            }
        }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
728x90