一、HttpURLConnection
object HttpUtil {
fun getRequest(url: String, params: Map<String, String>, listener: OnRequestListener) {
val sb = StringBuffer(url)
sb.append("?")
if (params.isNotEmpty()) {
for (map in params.entries) {
sb.append(map.key).append("=").append(map.value).append("&")
}
}
sb.deleteCharAt(sb.lastIndex)
val path = URL(sb.toString())
val conn: HttpURLConnection = path.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 8000
conn.readTimeout = 8000
conn.doInput = true
conn.doOutput = true
conn.outputStream.write(sb.toString().toByteArray(charset("UTF-8")))
conn.outputStream.close()
conn.connect()
try {
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
val inputStream = conn.inputStream
val outputStream = ByteArrayOutputStream()
val buffer = ByteArray(1024)
var len = 0
while (inputStream.read(buffer).also { len = it } != -1) {
outputStream.write(buffer, 0, len)
}
inputStream.close()
outputStream.close()
val str = outputStream.toString()
listener.onSuccess(str)
}
} catch (e: Exception) {
e.printStackTrace()
listener.onError(e.toString())
} finally {
conn.disconnect()
}
}
fun postRequest(url: String, params: Map<String, String>, listener: OnRequestListener) {
val sb = StringBuffer()
if (params.isNotEmpty()) {
for ((key, value) in params) {
sb.append(key).append("=").append(value).append("&")
}
sb.deleteCharAt(sb.length - 1)
}
val path = URL(url)
val conn = path.openConnection() as HttpURLConnection
conn.requestMethod = "POST"
conn.connectTimeout = 8000
conn.readTimeout = 8000
conn.doOutput = true
conn.doInput = true
val outputStream = conn.outputStream
outputStream.write(sb.toString().toByteArray(charset("UTF-8")))
outputStream.close()
conn.connect()
try {
if (conn.responseCode == HttpURLConnection.HTTP_OK) {
val inputStream = conn.inputStream
val outputStream = ByteArrayOutputStream()
val buffer = ByteArray(1024)
var len = 0
while (inputStream.read(buffer).also { len = it } != -1) {
outputStream.write(buffer, 0, len)
}
inputStream.close()
outputStream.close()
val str = outputStream.toString()
listener.onSuccess(str)
}
} catch (e: Exception) {
e.printStackTrace()
listener.onError(e.toString())
} finally {
conn.disconnect()
}
}
interface OnRequestListener {
fun onSuccess(response: String)
fun onError(error: String)
}
}
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
private val url = "https://www.baidu.com/"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initView()
}
private fun initView() {
binding.btnTest.setOnClickListener {
Thread {
HttpUtil.postRequest(url, mapOf(), object : OnRequestListener {
override fun onSuccess(response: String) {
Log.d("main", response)
}
override fun onError(error: String) {
Log.d("main", error)
}
})
}.start()
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_test"
android:layout_width="200dp"
android:layout_height="50dp"
android:text="测试" />
</LinearLayout>
二、OKHttp
object OkHttpUtil {
private val mOkHttpClient: OkHttpClient = OkHttpClient()
init {
init()
}
private fun init() {
val interceptor = HttpLoggingInterceptor { message: String ->
Log.d("okhttp", message)
}
OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.retryOnConnectionFailure(true)
.addInterceptor(interceptor)
.build()
}
fun getRequest(url: String, params: Map<String, String>, listener: OnRequestListener) {
val sb = StringBuffer(url)
sb.append("?")
if (params.isNotEmpty()) {
for (map in params.entries) {
sb.append(map.key).append("=").append(map.value).append("&")
}
}
sb.deleteCharAt(sb.lastIndex)
val request = Request.Builder()
.url(sb.toString())
.method("GET", null)
.build()
mOkHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
listener.onError(e.toString())
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
response.body?.let { listener.onSuccess(it.string()) }
}
}
})
}
fun postRequest(url: String, params: Map<String, String>, listener: OnRequestListener) {
val body = FormBody.Builder()
if (params.isNotEmpty()) {
for ((key, value) in params) {
body.add(key, value)
}
}
val request = Request.Builder()
.url(url)
.post(body.build())
.build()
mOkHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
listener.onError(e.toString())
}
override fun onResponse(call: Call, response: Response) {
if (response.isSuccessful) {
response.body?.let { listener.onSuccess(it.string()) }
}
}
})
}
interface OnRequestListener {
fun onSuccess(response: String)
fun onError(e: String)
}
}