今日、HttpURLConnection を使用しているときに、この非常に奇妙なことに遭遇しました。基本的にURLからデータを読み取り、データを(GSONを使用してJavaオブジェクトに解析した後)Javaオブジェクトに保存する以下のコードがあります。データは、シリアル化してファイルに保存した別のオブジェクトにも同時に保存されます。URL にアクセスできない場合は、ファイルからデータを読み取ります。URL は、VPN 経由でのみアクセスできる安全な URL です。そこで、プログラムをテストするために、VPN から切断して、ファイルからデータを読み取れるかどうかを確認しました。以下の最初のコードでは null ポインターがスローされますが、2 番目のコードではスローされません。ご覧のとおり、唯一の違いは、2 番目の例で HttpURLConnection を使用していることです。それを使用するとどのように役立ちますか?誰かが似たようなことに遭遇しましたか、それとも私は何かを見落としていますか? ;)
URL にアクセスできない場合に 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();
}
}