kotlin 发送请求
fun http(uri: String, requestMethod: String, postJson: String?): String {
val buffer: BufferedReader
val url = URL(uri)
val con = url.openConnection() as HttpURLConnection
con.requestMethod = requestMethod
con.setRequestProperty("Content-Type", "application/json;charset=UTF8")
//允许写出
con.doOutput = true
//允许读入
con.doInput = true
//不使用缓存
con.useCaches = false
//得到响应码
val responseCode = con.responseCode
if (postJson != null){
con.requestProperties["paramVO2"] = arrayListOf(postJson)
}
if (responseCode == HttpURLConnection.HTTP_OK) {
//得到响应流
val inputStream = con.inputStream
//将响应流转换成字符串
val resultBuffer = StringBuffer()
var line: String?
buffer = BufferedReader(InputStreamReader(inputStream, "UTF8"))
while (true) {
line = buffer.readLine()
if (line == null) {
break
}
resultBuffer.append(line)
}
return resultBuffer.toString()
}
return ""
}