HttpURLConnection帮助我避免了NullPointerException

时间:2013-08-18 00:27:31

标签: java

今天使用HttpURLConnection时遇到了这个非常奇怪的事情。我有以下代码,它基本上从URL读取数据,并将数据(在使用GSON解析为java对象之后)存储到Java对象中。数据也同时存储在我已序列化并保存到文件的另一个对象中。如果我的URL无法访问,我会从文件中读取数据。 URL是一个安全的URL,我只能通过VPN访问。因此,为了测试我的程序,我从VPN断开连接,看看我是否能够从文件中读取数据。下面的第一个代码抛出一个空指针,而第二个代码没有。您可以看到的唯一区别是我在第二个示例中使用HttpURLConnection。如何使用它有帮助?有人遇到类似的东西,还是我忽略了什么? ;)

无法访问网址时抛出nullpointer的代码 -

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

运行正常的代码

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

0 个答案:

没有答案