【问题标题】:Can't receive a value from HttpURLConnection.getResponseCode when using AsyncTask?使用 AsyncTask 时无法从 HttpURLConnection.getResponseCode 接收值?
【发布时间】:2019-12-18 01:44:39
【问题描述】:

我正在尝试构建一个使用 OpenWeatherMap API 的应用。

我知道我无法从主线程发送 HTTP 请求。所以我改用 AsyncTask。

这是我运行 AsyncTask 的 MainActivity 类:

TextView txtView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtView = (TextView)findViewById(R.id.myTextID);

    MyTask task = new MyTask(MainActivity.this, txtView);
    task.execute();

}

下面是 MyTask 类。这是我向 URL 发送 GET 请求并尝试获取响应代码的地方。

public class MyTask extends AsyncTask<String, String, String>{

    Context context;
    TextView txtView;
    MyTask (Context context, TextView txtView)
    {
        this.context = context;
        this.txtView = txtView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... voids) {

        HttpURLConnection connection = null;
        BufferedReader reader;
        String line;
        StringBuffer responseContent = new StringBuffer();
        String x = "No response code";



        try {
            URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=london&appid=thisismyaccesstoken");

            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);

            x = Integer.toString(connection.getResponseCode());

        }
        catch(Exception e)
        {
           //exception handling done here
        }

        return x;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String s) {
        txtView.setText(s);
    }
}

我不想做任何花哨的加载栏的东西,所以我将 onProgressUpdate() 方法保持为空。

当我运行应用程序时,我的屏幕上出现“无响应代码”,这应该仅在 MyTask 类未能将 GET 请求中的响应代码保存到字符串 x 中时运行。

这是我第一次使用 AsyncTask。是不是我做错了什么?

【问题讨论】:

  • 使用 Logcat 检查与您可能收到的异常相关的堆栈跟踪(假设您的 catch 块正在记录它)。并考虑使用 OkHttp,以获得具有内置线程管理的更简单的现代 HTTP API。

标签: java android android-asynctask httpurlconnection


【解决方案1】:

修复它。出于某种原因,每当我尝试将错误打印到控制台(在 catch 块中)时,我的应用程序就会崩溃。因此,我没有将异常打印到控制台,而是将异常转换为字符串并将字符串保存在“x”中,如下所示:

catch(Exception e)
    {
       x = e.toString()
    }

这样整个异常都显示在我的应用程序的文本视图中。显然这是一个 SecurityException 因为我的应用程序没有访问互联网的权限。所以我只是在 AndroidManifest.xml 文件中添加了以下几行:

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

这解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2012-07-27
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多