问题描述
我正在android studio中编程。我有一个按钮,发送一个http请求。当我单击按钮时,我的应用程序崩溃了!
有我的代码
MainActivity.kt
package com.example.messager
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import java.net.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun onclick(v:View){
URL ("https://google.com/").readText()
}
}
请帮帮我!我真的很想发送获取http请求
解决方法
尝试联系域https://google.com/
Executors.newSingleThreadExecutor().execute({
val data = URL("https://google.com/").readText()
simpleTextView.post { simpleTextView.text = data }
})
您可以联系资源并从中获取所需的信息
,打开URL的最简单,最快的方法是通过Intents
从Android应用中打开Chrome浏览器。在您的onClick方法中添加以下代码行。
val uri: Uri = Uri.parse("https://www.google.com")
val intent = Intent(Intent.ACTION_VIEW,uri)
startActivity(intent)
但是,如果要向端点发送GET请求,建议您使用网络客户端。例如:Retrofit或Volley。
使用Volley发送GET请求的示例:
val textView = findViewById<TextView>(R.id.text)
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "https://www.google.com"
// Request a string response from the provided URL.
val stringRequest = StringRequest(Request.Method.GET,url,Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
textView.text = "Response is: ${response.substring(0,500)}"
},Response.ErrorListener { textView.text = "That didn't work!" })
// Add the request to the RequestQueue.
queue.add(stringRequest)
您可以了解有关此here
的更多信息