要求:上面是地址栏和Go 按钮,在地址栏中输入网址,点击Go 时,中间区域的上部会加载网页,下部会显示网页的源代码。
注意:需要在AndroidManifest文件中加入权限声明
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity主要代码
class MainActivity : AppCompatActivity() {
lateinit var url:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button:Button = findViewById(R.id.button)
val editText:EditText = findViewById(R.id.edittext)
button.setOnClickListener {
url = editText.text.toString()
val webView:WebView = findViewById(R.id.webview)
webView.webViewClient = WebViewClient()
webView.loadUrl(url)
sendRequestWithHttpURLConnection()
}
}
private fun sendRequestWithHttpURLConnection(){
thread {
var connection:HttpURLConnection ?= null
try{
val response = StringBuilder()
val url = URL(url)
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())
}catch (e:Exception){
e.printStackTrace()
}finally {
connection?.disconnect()
}
}
}
private fun showResponse(response:String){
val responseText:TextView = findViewById(R.id.responseText)
runOnUiThread{
responseText.text = response
}
}
}
布局页面主要代码:
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<EditText
android:id="@+id/edittext"
android:layout_width="340dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
</LinearLayout>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="320dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/responseText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>