Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor) Android

I try to read json file from the URL in my Android Project. But strange situation happens. StringBuilder successfully gets first few characters but then I get java.net.SocketException: recvfrom failed: EBADF (Bad file descriptor)

Why I get this exception?

What is wrong with my code?)

JSON: http://inlyfortesting.ucoz.net/artists.json

My 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;
        }
    }
like image 508
Igor Nikolaev Avatar asked May 30 '26 22:05

Igor Nikolaev


1 Answers

You're disconnecting the connection before you read from it. You need to do that afterwards.

Surely this is obvious?

EDIT You don't need to call disconnect() at all here. Closing the returned InputStream is required by the caller, and that is sufficient. All disconnect() does is disable the connection pooling, which you don't want either.

like image 124
user207421 Avatar answered Jun 01 '26 12:06

user207421