【发布时间】:2018-09-27 17:27:43
【问题描述】:
我正在尝试使用以下代码从 JSON 端点获取令牌:
public class FetchToken extends AsyncTask<String, Void, Void> {
String data = "";
String token = "";
public TokenDelegate delegate = null;
@Override
protected Void doInBackground(String... identity) {
try {
if (identity.length == 1) {
URL url = new URL(identity[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONObject JO = new JSONObject(data);
token = JO.get("token").toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
Log.d("token", token);
//delegate.processFinish(token);
super.onPostExecute(aVoid);
}
}
我尝试在每一行之后打印到调试日志,似乎InputStream inputStream = httpURLConnection.getInputStream(); 行永远不会完成,其余代码也不会执行。但是,这发生在 AsyncTask 内部,并且该 AsyncTask 的 onPostExecute 方法正在触发,就好像任务已经完成一样,但它看起来好像已经完成了。
似乎没有执行任何 catch 块,当我检查 Android Profiler 中的网络面板时,请求说它没有传回任何东西。但是,在浏览器中访问 JSON 端点会使一切恢复正常。
希望有人知道问题可能是什么。我试图用谷歌搜索无济于事。如果需要更多信息,请告诉我。谢谢。
【问题讨论】:
-
the onPostExecute method of that AsyncTask is firing- 那么httpURLConnection.getInputStream()正在工作,如果(identity.length == 1)因为这是一个阻塞调用,你确定你没有捕获异常并返回null- 检查logcat ?还要确保关闭finally块中的流 -
你找到正确的解决方案了吗?
-
就我而言,这是因为我的模拟器无法连接到互联网
标签: java android android-studio android-asynctask