android HttpURLConnection

247 阅读1分钟

1.NetActivity

class NetActivity : AppCompatActivity() {
    private var result = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_net)

        button9.setOnClickListener {
            thread {
                result =
                    NetworkUtil.requestDataByGet("http://www.imooc.com/api/teacher?type=2&page=1")
                runOnUiThread {
                    result = NetworkUtil.decode(result)
                    textView.text = result
                }
            }
        }
        button10.setOnClickListener {
            if (result.isNotEmpty()) {
                val handleJsonData = NetworkUtil.handleJsonData(result)
                textView.text = handleJsonData
            }
        }
    }
}

2.NetworkUtil

object NetworkUtil {
    fun requestDataByGet(s: String): String {
        var result: String = ""
        val url = URL(s)
        val connection = url.openConnection() as HttpURLConnection
        connection.apply {
            connectTimeout = 10000
            requestMethod = "GET"
            setRequestProperty("Content-Type", "application/json")
            setRequestProperty("Charset", "UTF-8")
            setRequestProperty("Accept-Charset", "UTF-8")
            connect()
        }
        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            val inputStream = connection.inputStream
            result = stream2String(inputStream)
        } else {
            val responseMessage = connection.responseMessage
            Log.i("tag-->", "responseMessage:$responseMessage")
        }
        return result
    }

    fun requestDataByPost(s: String): String {
        var result: String = ""
        val url = URL(s)
        val connection = url.openConnection() as HttpURLConnection
        connection.apply {
            // 设置运行输入,输出:
            doInput = true
            doOutput = true
            // Post方式不能缓存,需手动设置为false
            useCaches = false
            connect()
        }
        // 我们请求的数据:
        val data = ("username=" + URLEncoder.encode("imooc", "UTF-8")
                + "&number=" + URLEncoder.encode("15088886666", "UTF-8"))
        // 获取输出流
        val out = connection.outputStream
        out.write(data.toByteArray())
        out.flush()
        out.close()

        val responseCode = connection.responseCode
        if (responseCode == HttpURLConnection.HTTP_OK) {
            val inputStream = connection.inputStream
//            result = stream2String(inputStream)
            val reader: Reader = InputStreamReader(inputStream, "UTF-8")
            val buffer = CharArray(1024)
            reader.read(buffer)
            result = String(buffer)
            reader.close()
        } else {
            val responseMessage = connection.responseMessage
            Log.i("tag-->", "responseMessage:$responseMessage")
        }
        return result
    }

    private fun stream2String(inputStream: InputStream): String {
        val baos = ByteArrayOutputStream()
        val buffer = ByteArray(1024)
        var len: Int
        //let会改变inputStream.read(buffer)的值,所以这里用also
        while (inputStream.read(buffer).also { len = it } != -1) {
            baos.write(buffer, 0, len)
        }
        baos.close()
        inputStream.close()
        val byteArray = baos.toByteArray()
        return String(byteArray)
    }


    //将Unicode字符转换为UTF-8类型字符串
    fun decode(unicodeStr: String): String {
        val retBuf = StringBuilder()
        val maxLoop = unicodeStr.length
        run {
            var i = 0
            while (i < maxLoop) {
                if (unicodeStr[i] == '\\') {
                    if (i < maxLoop - 5
                        && (unicodeStr[i + 1] == 'u' || unicodeStr[i + 1] == 'U')
                    ) try {
                        retBuf.append(unicodeStr.substring(i + 2, i + 6).toInt(16).toChar())
                        i += 5
                    } catch (localNumberFormatException: NumberFormatException) {
                        retBuf.append(unicodeStr[i])
                    } else {
                        retBuf.append(unicodeStr[i])
                    }
                } else {
                    retBuf.append(unicodeStr[i])
                }
                i++
            }
        }
        return retBuf.toString()
    }

    fun handleJsonData(json: String): String {
        val jsonObject = JSONObject(json)
        val lessonResult = LessonResult(0, mutableListOf(), "")
        val lessonList: MutableList<LessonResult.Data> = mutableListOf()
        val status = jsonObject.getInt("status")
        val lessons = jsonObject.getJSONArray("data")
        if (lessons.length() > 0) {
            for (index in 0 until lessons.length()) {
                val item = lessons[0] as JSONObject
                val id = item.getInt("id")
                val name = item.getString("name")
                val smallPic = item.getString("picSmall")
                val bigPic = item.getString("picBig")
                val description = item.getString("description")
                val learner = item.getInt("learner")
                val lesson: LessonResult.Data = LessonResult.Data(0, "", "", "", "", 0)
                lesson.id = id
                lesson.name = name
                lesson.picSmall = smallPic
                lesson.picBig = bigPic
                lesson.description = description
                lesson.learner = learner
                lessonList.add(lesson)
            }
            lessonResult.status = status
            lessonResult.data = lessonList
        }
        return lessonResult.toString()
    }
}