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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With