【发布时间】: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