728x90

Java 코드로 만든 코드를 코틀린으로 변환하고 테스트를 하니까 제대로 동작이 안된다.

코드 일부를 수정해주고 나서 동작에 제대로 된다.

Volley 라이브리를 사용하면 간단하게 해결될 사항이지만 HttpURLConnection 으로 서버 데이터를 안드로이드폰으로 가져오는 방법도 알아두면 좋을 거 같아서 테스트하고 적어둔다.


private fun UpgradeChk() {
     val builder = Uri.Builder()
         .appendQueryParameter("os", "a")
     val postParams = builder.build().encodedQuery
     val getlastVersion = getlastVersion()
     getlastVersion.execute( Value.IPADDRESS + "/lastVersion.php", postParams)
 }

inner class getlastVersion : AsyncTask<String, Void, String>() {
    override fun doInBackground(vararg params: String): String {
        return try {
            HttpURLComm.getJson(params[0], params[1])
        } catch (e: Exception) {
            String.format("Exception: " + e.message)
        }
    }

    override fun onPostExecute(response: String) {
        version = Value.VERSION // 앱 버전
        version = version.replace("[^0-9]".toRegex(), "") // 버전에서 숫자만 추출
        Log.e("WEB", "Response: $response")
        val Response = response.replace("[^0-9]".toRegex(), "") // 버전에서 숫자만 추출
        println("Server Version : $Response")
        if (version.toInt() < Response.toInt()) { // 서버 버전이 더 높으면
            UpgradeProcess()
        } else {
            AutoLoginProgress()
        }
    }
}
 

import android.util.Log
import android.webkit.CookieManager
import com.link2me.android.enode.Value
import java.io.BufferedReader
import java.io.DataOutputStream
import java.net.HttpURLConnection
import java.net.URL

object HttpURLComm  {
    // serverURL : JSON 요청을 받는 서버의 URL
    // postParams : POST 방식으로 전달될 입력 데이터
    // 반환 데이터 : 서버에서 전달된 JSON 데이터
    @JvmStatic
    @Throws(Exception::class)
    fun getJson(serverUrl: String?, postParams: String?): String {
        try {
            Thread.sleep(100)
            val url = URL(serverUrl)
            val conn = url.openConnection() as HttpURLConnection
            // 세션 쿠키 전달
            val cookieString = CookieManager.getInstance().getCookie(Value.IPADDRESS)
            val sb = StringBuilder()
            if (conn != null) { // 연결되었으면
                //add request header
                conn.requestMethod = "POST"
                conn.setRequestProperty("USER-AGENT", "Mozilla/5.0")
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
                conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5")
                if (cookieString != null) {
                    conn.setRequestProperty("Cookie", cookieString)
                    Log.e("PHP_getCookie", cookieString)
                }
                conn.connectTimeout = 10000
                conn.readTimeout = 10000
                conn.useCaches = false
                conn.defaultUseCaches = false
                conn.doOutput = true // POST 로 데이터를 넘겨주겠다는 옵션
                conn.doInput = true

                // Send post request
                val wr = DataOutputStream(conn.outputStream)
                wr.writeBytes(postParams)
                wr.flush()
                wr.close()
                val responseCode = conn.responseCode
                Log.e("TAG","GET Response Code : $responseCode")
                if (responseCode == HttpURLConnection.HTTP_OK) { // 연결 코드가 리턴되면
                    val allText: String = conn.inputStream.bufferedReader().use(BufferedReader::readText)
                    sb.append(allText.trim())
                }
            }
            conn.disconnect()
            return sb.toString()
            // 수행이 끝나고 리턴하는 값은 다음에 수행될 onProgressUpdate 의 파라미터가 된다
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {

        }
        return ""
    }
}


https://github.com/irontec/android-kotlin-samples/blob/master/KotlinTest/app/src/main/java/com/irontec/examples/kotlintest/HttpUrlConnectionAsyncActivity.kt

를 참조하여 코드를 약간 보완했다.

object HttpURLComm {
    // serverURL : JSON 요청을 받는 서버의 URL
    // postParams : POST 방식으로 전달될 입력 데이터
    // 반환 데이터 : 서버에서 전달된 JSON 데이터
    @JvmStatic
    @Throws(Exception::class)
    fun getJson(serverUrl: String?, postParams: String?): String {
        Thread.sleep(100)
        val url = URL(serverUrl)
        val httpClient = url.openConnection() as HttpURLConnection
        // 세션 쿠키 전달
        val cookieString = CookieManager.getInstance().getCookie(Value.IPADDRESS)
        val sb = StringBuilder()
        if (httpClient != null) { // 연결되었으면
            //add request header
            httpClient.requestMethod = "POST"
            httpClient.setRequestProperty("USER-AGENT", "Mozilla/5.0")
            httpClient.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
            httpClient.setRequestProperty("Accept-Language", "en-US,en;q=0.5")
            if (cookieString != null) {
                httpClient.setRequestProperty("Cookie", cookieString)
                Log.e("PHP_getCookie", cookieString)
            }
            httpClient.connectTimeout = 10000
            httpClient.readTimeout = 10000
            httpClient.useCaches = false
            httpClient.defaultUseCaches = false
            httpClient.doOutput = true // POST 로 데이터를 넘겨주겠다는 옵션
            httpClient.doInput = true

            // Send post request
            val wr = DataOutputStream(httpClient.outputStream)
            wr.writeBytes(postParams)
            wr.flush()
            wr.close()

            if (httpClient.responseCode == HttpURLConnection.HTTP_OK) {
                try {
                    val stream = BufferedInputStream(httpClient.inputStream)
                    val data: String = readStream(inputStream = stream)
                    return data
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    httpClient.disconnect()
                }
            } else {
                println("ERROR ${httpClient.responseCode}")
            }
        }
        return ""
    }

    fun readStream(inputStream: BufferedInputStream): String {
        val bufferedReader = BufferedReader(InputStreamReader(inputStream))
        val stringBuilder = StringBuilder()
        bufferedReader.forEachLine { stringBuilder.append(it) }
        return stringBuilder.toString()
    }
}
 



블로그 이미지

Link2Me

,