HttpURLConnection helped me avoid NullPointerException
I encountered this really strange thing while using the HttpURLConnection
today. I have the below code that basically reads data from a URL, and
stores the data (after parsing it to a java object using GSON) into a Java
object. The data is also simultaneously stored in another object that I
have serialized and saved to a file. In the event my URL is not
accessible, I read the data from the file. The URL is a secure URL that I
can only access over the VPN. So to test my program, I disconnected from
the VPN to see if I am able to read data from the file. The first code
below throws me a null pointer, while the second one doesn't. The only
difference as you can see is I am using HttpURLConnection in the second
example. How does using it help? Anyone encountered something similar, or
am I overlooking something? ;)
Code that throws nullpointer when URL can't be accessed -
public static void getInfoFromURL() throws IOException {
Gson gson = null;
URL url = null;
BufferedReader bufferedReader = null;
String inputLine = "";
try {
gson = new Gson();
url = new URL(addressURL);
bufferedReader = new BufferedReader(new
InputStreamReader(url.openStream()));
while ((inputLine = bufferedReader.readLine()) != null) {
addressData = ((AddressData)
gson.fromJson(inputLine,AddressData.class));
}
} catch (MalformedURLException mue) {
logger.error("Malformed URL exception " + mue+ " occured while
accessing the URL ");
} catch (IOException ioe) {
logger.error("IO exception " + ioe+ " occured while accessing the
URL ");
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
Code that works fine:
public static void getInfoFromURL() throws IOException {
Gson gson = null;
URL url = null;
BufferedReader bufferedReader = null;
HttpURLConnection connection =null;
String inputLine = "";
try {
gson = new Gson();
url = new URL(addressURL);
connection = (HttpURLConnection) url.openConnection();
//This seems to be helping
connection.connect();
bufferedReader = new BufferedReader(new
InputStreamReader(url.openStream()));
while ((inputLine = bufferedReader.readLine()) != null) {
addressData = ((AddressData)
gson.fromJson(inputLine,AddressData.class));
}
} catch (MalformedURLException mue) {
logger.error("Malformed URL exception " + mue+ " occured while
accessing the URL ");
} catch (IOException ioe) {
logger.error("IO exception " + ioe+ " occured while accessing the
URL ");
} finally {
if (bufferedReader != null)
bufferedReader.close();
}
}
No comments:
Post a Comment