2011-02-11 17 views
0

訪問JSON對象,當我嘗試使用訪問JSON對象下面的代碼「空指針異常」使用URL

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


    } 

然後我得到空指針例外,我無法弄清楚它是什麼,請幫助我

感謝您的時間

回答

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所所以你的方法將成功返回一個列表。

+0

感謝您的快速回復。我嘗試使用DefaultHttpClient.I得到錯誤 - :(和warnig「顯示狀態在非活動InputConnection」.Null指針異常對於輸入流 – DroidBot 2011-02-11 13:29:44