android 开发中的okHttp的使用

1、首先在gradle中引用这个依赖

implementation 'com.squareup.okhttp3:okhttp:4.1.0'

2、创建一个函数runOnOkHttp()来进行测试

private fun runOnOkHttp() {
        textView = findViewById(R.id.text_view)
        thread {
            try {
                //打开浏览器
                val client = OkHttpClient()
                //生成一个请求
                val request = Request.Builder()
                    .url("http://t.weather.sojson.com/api/weather/city/101010100")
                    .build()
                //执行请求
                val response = client.newCall(request).execute()
                //获取数据
                val responseData = response.body?.string()
                runOnUiThread{
                    textView.text = responseData.toString()
                }
            }catch (e:Exception){
                e.printStackTrace()
            }finally {

            }
        }
    }

在这个代码中,4个步骤就是常规使用okHttp的方法。

完整代码如下:

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.TextView
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    lateinit var textView: TextView
    lateinit var webViewBtn: Button
    lateinit var webViewContent:WebView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //链接UI
        webViewBtn = findViewById(R.id.btn_web_view)
        webViewContent = findViewById(R.id.web_view_content)
        textView = findViewById(R.id.text_view)


        // 按钮点击事件
        webViewBtn.setOnClickListener {
            // 调用浏览器内核
            webViewContent.settings.javaScriptEnabled=true
            webViewContent.webViewClient = WebViewClient()
            webViewContent.loadUrl("https://ybu.edu.cn")
            // 读取网页源代码
            // 开启线程
            //runOnHttpUrlConn()
            runOnOkHttp()


        }

    }

    private fun ShowResponseWithJson(response:String) {
        try {
            //获取花括号里的key:value结构数据
            val allData = JSONObject(response)
            val tmp = allData.getString("message")
            Log.d("JsonObject", tmp)
        }catch (e:Exception){
            e.printStackTrace()
        }finally {

        }
    }

    private fun runOnOkHttp() {
        textView = findViewById(R.id.text_view)
        thread {
            try {
                //打开浏览器
                val client = OkHttpClient()
                //生成一个请求
                val request = Request.Builder()
                    .url("http://t.weather.sojson.com/api/weather/city/101010100")
                    .build()
                //执行请求
                val response = client.newCall(request).execute()
                //获取数据
                val responseData = response.body?.string()
                runOnUiThread{
                    textView.text = responseData.toString()
                    ShowResponseWithJson(responseData.toString())
                }
            }catch (e:Exception){
                e.printStackTrace()
            }finally {

            }
        }
    }

    private fun runOnHttpUrlConn() {
        textView = findViewById(R.id.text_view)
        thread {
            // 网页内容保存变量
            val response = StringBuilder()
            // 网络空白连接对象
            var conn : HttpURLConnection? = null
            // 错误捕捉
            try {
                val url = URL("http://t.weather.sojson.com/api/weather/city/101010100")
                conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"
                conn.connectTimeout = 8000
                conn.readTimeout = 8000
                val input = conn.inputStream
                val reader = BufferedReader(InputStreamReader(input))
                reader.use {
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                Log.d("WebView", response.toString())

                runOnUiThread {
                    textView.text = response.toString()
                }

            } catch (e: Exception){
                e.printStackTrace()
            } finally {
                conn?.disconnect()
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值