Android 第三十二章 网络请求

一、HttpURLConnection

//权限 <uses-permission android:name="android.permission.INTERNET"/>
object HttpUtil {
    /**
     * get 请求
     */
    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()
        }
    }

    /**
     * post 请求
     */
    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)
    }
}
/**
 * viewBinding
 * 绑定视图
 * 在build.gradle  android 下 添加
buildFeatures {
viewBinding true
}
 */

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

/**
 *      权限
 *     implementation 'com.squareup.okhttp3:okhttp:4.10.0'
       implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
* */

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()
    }

    /**
     * get 请求
     */
    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("&")
            }
        }
//        Callback
        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()) }
                }
            }

        })
    }

    /**
     * post 请求
     */
    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)
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值