Android Kotlin中的HTTP GET

问题描述

我正在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

的更多信息

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...