url.openStream()仅为一个url提供NullPointerException

时间:2015-01-21 15:58:22

标签: java android nullpointerexception

请不要将其标记为重复,因为我在发布之前已经搜索过Stackoverflow,并找到了这个解决方案,

url.openstream() or urlconnection.getinputstream() raise nullpointerexception on valid URL

但是这个解决方案也不起作用。

问题是我在这个网址上试图openStream>我的Android应用http://www.techworld.com/security/rss

但它总是给NullPointerException

我首先检查连接以查看连接是否成功,

connection.getResponseCode();

并返回200,以便连接正常。

然后根据可用的解决方案,我将JRE版本从1.7更改为1.6,但这仍然无法正常工作。

当我尝试openStream其他网址时,他们使用相同的代码完全正常工作,但上面的链接提供了NPE

这是代码,

URL mylink = new URL ("http://www.techworld.com/security/rss");

HttpURLConnection connection;
connection = (HttpURLConnection) myLink.openConnection();   
connection.connect();

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    try {
        domObject = new DOM(myLink.openStream());
        domObject.start();

    } catch (Exception e) {
        Log.e(TAG,e+" " + host);
    }    
}

在上面的代码中,host = myLink.getHost();

我还想提一下,当我将此代码作为Java项目而不是Android项目运行时,它会加载查找并且不会抛出NPE

这可能是什么问题?

这是logCat,它只显示一行错误

01-21 20:46:11.575: E/testApp(30335): java.lang.NullPointerException www.techworld.com

1 个答案:

答案 0 :(得分:2)

至少这段代码有效:

URL url;
try {
    url = new URL("http://www.techworld.com/security/rss");
    HttpURLConnection httpURLConnection;
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.connect();
    if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        StringBuffer stringBuffer = new StringBuffer();
        try {
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                stringBuffer.append(inputLine).append("\n");
            }
        } finally {
            bufferedReader.close();
        }

        System.out.println(stringBuffer.toString());
        }
} catch (IOException e) {
    e.printStackTrace();
}

我认为您的代码尝试两次打开连接。虽然第一个连接未关闭,但您尝试连接另一个 myLink.openStream()。使用 connection.getInputStream()

可能更好