Http访问网络模板-兼okHttp

代码:

  • Manifest:
<manifest ...>
...
<uses-permission android:name="android.permission.INTERNET"/>
...
<application>
...
<activity android:name=".web.HttpURLActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
  • Kotlin:

​activity:​

class HttpURLActivity : AppCompatActivity() {

private lateinit var httpUrlBinding: ActivityHttpurlBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
httpUrlBinding = ActivityHttpurlBinding.inflate(layoutInflater)
setContentView(httpUrlBinding.root)

httpUrlBinding.httpUrlSendRequest.setOnClickListener {
sendRequestWithHttpURLConnection()
}
}

private fun sendRequestWithHttpURLConnection() {
//开启线程发起的网络请求
thread {
var connection: HttpURLConnection? = null
try {
/*val response = StringBuilder()
val url = URL("https://www.baidu.com")
connection = url.openConnection() as HttpURLConnection
connection.connectTimeout = 8000
connection.readTimeout = 8000
val input = connection.inputStream
//下面对获取的输入流进行读取
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine {
response.append(it)
}
}
showResponse(response.toString())*/
//okhttp
val client = OkHttpClient()
val request = Request.Builder()
.url("https://www.baidu.com")
.build()
val response = client.newCall(request).execute()
val responseData = response.body?.string()
if (responseData != null) showResponse(responseData)
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
}
}

private fun showResponse(response: String) {
runOnUiThread {
//在这里进行UI操作,将结果显示到界面上
httpUrlBinding.httpUrlResponseText.text = response
}
}
}
  • Layout:

​activity_httpurl:​

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/httpUrl_sendRequest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/httpUrl_responseText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
  • gradle:

​app:​

implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'