gpt4 book ai didi

android - HttpUrlConnection.connect失败

转载 作者:行者123 更新时间:2023-12-02 13:32:58 25 4
gpt4 key购买 nike

我一直在尝试创建一个小的应用程序,该应用程序连接到editText中的url并返回状态代码。

这是onCreate代码:

 override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
val url = editText.text.toString()
var connection: HttpURLConnection? = null
if (URLUtil.isValidUrl(url)) {
connection = URL(url).openConnection() as HttpURLConnection
var thr = Thread {
connection.connect()
val code = connection.responseCode
runOnUiThread {
if (code != 404 && code != 500) {
textView.text = "Ok"
} else {
textView.text = "Failed"
}
}

}
thr.start()
thr.join()
} else {
textView.text = "Failed"
}
}

问题在于,只要URL有效,.connect()方法中就会发生运行时错误。 Internet权限在android list 中设置。是什么原因导致该问题?
E/AndroidRuntime: FATAL EXCEPTION: Thread-2
Process: com.example.company.myapplication, PID: 27183
java.net.SocketException: socket failed: EPERM (Operation not permitted)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
at com.example.company.myapplication.MainActivity$onCreate$1$thr$1.run(MainActivity.kt:25)
at java.lang.Thread.run(Thread.java:919)

最佳答案

对于那些没有阅读聊天的人:
URLUtil.isValidUrl(url)不会检查所讨论的URL是否实际上可以解析为网站/服务器。这意味着当在不存在的网站/服务器上调用connect时,将引发异常,因为没有要连接的内容。

关于android - HttpUrlConnection.connect失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60249734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com