Reputation: 6852
I am trying to access json object using following code
http://epubreader.XXXXXXX.net/public/json/books.json
try
{
InputStream in = openHttpConnection("http://epubreader.feathersoft.net
/public/json/books.json");
Data=new byte[in.available()];
in.read(Data);
}
catch(IOException e)
{
Log.e("url", e.getLocalizedMessage()+e.getCause()+e.getStackTrace());
}
}
private InputStream openHttpConnection(String url_send) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(url_send);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}
Then I got Nullpointer exception I cannot figure out what it is please help me
Thanks for your time
Upvotes: 0
Views: 1872
Reputation: 73484
What line is the NPE on? If the response != HttpURLConnection.HTTP_OK, then openHttpConnection will return null and you will get an NPE on in.read(Data). You might want to do something like this.
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
} else {
throw new IOException("Bad Response Received");
}
And also you don't need the try and catch block in openHttpConnection, just let it throws the IOException and handle it like you are in the code above.
It might be cleaner to use the Apache HttpClient classes in the sdk. Something like.
HttpClient client = AndroidHttpClient.newInstance("myUserAgent");
HttpGet httpGet = new HttpGet("http://epubreader.feathersoft.net
/public/json/books.json");
HttpResponse response = client.execute(httpGet);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream inputStream = response.getEntity().getContent();
// read from stream
}
You could also use execute with a anonymous ResponseHandler so your method would return a List on success.
Upvotes: 1