Android HTTP URL连接显示空指针异常

时间:2010-10-26 10:22:37

标签: android

在我的Android应用程序中,我必须从服务器下载XML文件。我使用了下面显示的代码。有时它会显示getResponseCode()方法的空指针异常。 httpConn不为null。

                    public static byte[] getGprsConnData(String urlStr){
                    URL url = new URL(urlStr);
        URLConnection urlConn = url.openConnection();
        if(!(urlConn instanceof HttpURLConnection)){
        Log.e("Error", "connection is not an instance of HTTP connection");
            throw new IOException ("URL is not an Http URL");
        }
        httpConn = (HttpURLConnection)urlConn;
        if(httpConn == null){
            System.out.println("httpconnection is null");
        }else{
            System.out.println("httpconnection isn't null");
        }
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        System.out.println("getting http Connection ");
        httpConn.connect(); 
        System.out.println("http Connection established");
        int code = -1;
        try{
        code = httpConn.getResponseCode();
        }catch(Exception e){
            e.printStackTrace();
            Log.e("Exception", "while getting http response code");
        }
        System.out.println("http Connection response code" + code);
        if(httpConn != null && httpConn.getResponseCode()!= HttpURLConnection.HTTP_OK){
            return null;
        }
        System.out.println("getting inputStream");
        InputStream fromServer = httpConn.getInputStream();}

这种例外的原因是什么?

0 个答案:

没有答案