gpt4 book ai didi

java - 无法获取响应/状态代码,使用 HttpUrlConnection 总是得到空白异常

转载 作者:太空宇宙 更新时间:2023-11-04 09:13:17 25 4
gpt4 key购买 nike

我不知道发生了什么,但我的代码无法获取响应/状态代码,并且总是出现空白异常。

if (!GetS1.isEmpty() || !GetS1.equals("")) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
url = new URL(GetS1);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
urlConnection.connect();
final int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
ButtonS1.setEnabled(true);
ButtonS1.setText("ACTIVE");
} else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
ButtonS1.setText("BLOCKED");
} else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
ButtonS1.setText("DOWN");
} else {
ButtonS1.setText("UNKNOWN / BROKEN");
}
} catch (Exception e) {
Toast.makeText(Act_Details.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}

我错过了什么吗?我已经在 list 中设置了使用互联网的权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

最佳答案

首先,请发布完整的代码,或者至少发布上述代码(您提供的)所属的代码,假设您在一个单独的线程而不是 UI 线程中完成整个工作,您可以这样做:

    if (!GetS1.isEmpty() || !GetS1.equals("")) {
doNetworkCall();
}

然后创建一个方法:

    private void doNetworkCall(){

try {
url = new URL(GetS1);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
urlConnection.connect();
final int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
ButtonS1.setEnabled(true);
ButtonS1.setText("ACTIVE");
}
else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
ButtonS1.setText("BLOCKED");
}
else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
ButtonS1.setText("DOWN");
}
else {
ButtonS1.setText("UNKNOWN / BROKEN");
}
} catch (Exception e) {

Toast.makeText(Act_Details.this, ""+e,Toast.LENGTH_SHORT).show();
}
}

并检查屏幕上是否出现 Toast 并出现错误

关于java - 无法获取响应/状态代码,使用 HttpUrlConnection 总是得到空白异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59422680/

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