使用url访问json对象时出现“空指针异常”

时间:2011-02-11 12:30:24

标签: android web-services json

我正在尝试使用以下代码访问json对象

http://epubreader.XXXXXXX.net/public/json/books.json

        try
       {
          InputStream in = openHttpConnection("http://epubreader.feathersoft.net
          /public/json/books.json"); 
          Data=new byte[in.available()];
          in.read(Data);
        }
       catch(IOException e)
           {
           Log.e("url", e.getLocalizedMessage()+e.getCause()+e.getStackTrace());    
           }


   }

   private InputStream openHttpConnection(String url_send) throws IOException
   {

        InputStream in = null;
        int response = -1;

        URL url = new URL(url_send);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
           throw new IOException("Not an HTTP connection");

        try {
           HttpURLConnection httpConn = (HttpURLConnection) conn;
           httpConn.setAllowUserInteraction(false);
           httpConn.setInstanceFollowRedirects(true);
           httpConn.setRequestMethod("GET");
           httpConn.connect();

           response = httpConn.getResponseCode();
           if (response == HttpURLConnection.HTTP_OK) {
              in = httpConn.getInputStream();
           }
        } catch (Exception ex) {
           throw new IOException("Error connecting");
        }
        return in;
    }


  }   

然后我得到Nullpointer异常我无法弄清楚它是什么请帮助我

感谢您的时间

1 个答案:

答案 0 :(得分:1)

NPE在哪一行?如果响应!= HttpURLConnection.HTTP_OK,则openHttpConnection将返回null,您将在in.read(Data)上获得NPE。你可能想做这样的事情。

if (response == HttpURLConnection.HTTP_OK) {
     in = httpConn.getInputStream();
} else {
     throw new IOException("Bad Response Received");
}

而且你也不需要在openHttpConnection中使用try和catch块,只需让它抛出IOException并像上面的代码一样处理它。

在sdk中使用Apache HttpClient类可能更清晰。像。的东西。

HttpClient client = AndroidHttpClient.newInstance("myUserAgent");
HttpGet httpGet = new HttpGet("http://epubreader.feathersoft.net
          /public/json/books.json");
HttpResponse response = client.execute(httpGet);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    InputStream inputStream = response.getEntity().getContent();
    // read from stream
}

您还可以将execute与匿名ResponseHandler一起使用,以便您的方法在成功时返回List。