java.net.SocketException:recvfrom失败:EBADF(错误的文件描述符)Android

时间:2016-04-25 14:45:49

标签: java android json url socketexception

我尝试从Android项目中的URL读取json文件。但奇怪的情况发生了。 StringBuilder成功获取前几个字符,但后来我得到java.net.SocketException:recvfrom失败:EBADF(错误的文件描述符)

为什么我会遇到这个例外?

我的代码出了什么问题?)

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;
        }
    }

1 个答案:

答案 0 :(得分:3)

在您阅读之前,您已断开连接。之后你需要这样做。

当然这很明显?