在kotlin中使用net包提供的HttpURLConnection进行网络请求
POST
private fun post(json: String) {
Thread {
var conn: HttpURLConnection? = null
var out: PrintWriter? = null
var reader: BufferedReader? = null
try {
conn =
URL("http://127.0.0.1").openConnection() as HttpURLConnection
conn.setRequestProperty("accept", "*/*")
conn.setRequestProperty("connection", "Keep-Alive")
conn.setRequestProperty("user-agent", System.getProperty("http.agent"))
conn.doOutput = true
conn.doInput = true
conn.connectTimeout = 30 * 1000
conn.readTimeout = 30 * 1000
out = PrintWriter(OutputStreamWriter(conn.outputStream, "utf-8"))
//发送请求
out.print(json)
//flush 输出流缓冲
out.flush()
reader = BufferedReader(InputStreamReader(conn.inputStream, "utf-8"))
val bufferResult = StringBuffer()
reader.use { r ->
val temp = r.readLine()
if (temp != null) bufferResult.append(temp)
}
val responseCode = conn.responseCode
//请求成功
if (responseCode == 200) {
GLog.p(bufferResult.toString())
}
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
out?.let {
try {
it.close()
} catch (exInner: Exception) {
exInner.printStackTrace()
}
}
reader?.let {
try {
it.close()
} catch (exInner: Exception) {
exInner.printStackTrace()
}
}
conn?.let {
it.disconnect()
}
}
}.start()
}
GET
private fun post(url: String) {
Thread {
var conn: HttpURLConnection? = null
var reader: BufferedReader? = null
try {
conn =
URL(url).openConnection() as HttpURLConnection
conn.setRequestProperty("Accept-Charset", charset)
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
conn.setRequestProperty("user-agent", System.getProperty("http.agent"))
conn.doOutput = true
conn.doInput = true
conn.connectTimeout = 30 * 1000
conn.readTimeout = 30 * 1000
reader = BufferedReader(InputStreamReader(conn.inputStream, "utf-8"))
val bufferResult = StringBuffer()
reader.use { r ->
val temp = r.readLine()
if (temp != null) bufferResult.append(temp)
}
val responseCode = conn.responseCode
//请求成功
if (responseCode == 200) {
GLog.p(bufferResult.toString())
}
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
reader?.let {
try {
it.close()
} catch (exInner: Exception) {
exInner.printStackTrace()
}
}
conn?.let {
it.disconnect()
}
}
}.start()
}
评论区