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