【发布时间】:2016-04-26 00:37:32
【问题描述】:
我尝试从我的 Android 项目中的 URL 读取 json 文件。但奇怪的情况发生了。 StringBuilder 成功获取前几个字符,但随后我得到 java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
为什么会出现这个异常?
我的代码有什么问题?)
JSON:http://inlyfortesting.ucoz.net/artists.json
我的 JSONParser:
public JSONArray getJSONFromUrl(String urlAsString) {
// try to create JSONObject from string
try {
URL url = new URL(urlAsString);
new DownloadFileTask().execute(url).get();
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return jObj;
}
private class DownloadFileTask extends AsyncTask<URL, Integer, Long> {
StringBuilder sb;
protected Long doInBackground(URL... urls) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) urls[0].openConnection();
is = new BufferedInputStream(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
//file reading
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
sb = new StringBuilder();
int symbol;
int counter = 0;
while ((symbol = reader.read()) != -1) { //PROBLEM HERE
sb.append((char)symbol); //OR HERE
}
json = sb.toString();
is.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); //java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)
}
return null;
}
}
【问题讨论】:
-
connection.disconnect();。删除它。如果您已断开连接,您将无法再像现在尝试的那样阅读。 -
new DownloadFileTask().execute(url).get();。在那里调用 .get() 方法的编程非常糟糕。移除 get() 并将以下语句放在 onPostExecute 中。
标签: java android json url socketexception