HTTP connection HTTP URL shows null pointer exception

In my Android application, I need to download the XML files from the server. I used the code shown below. Sometimes it shows a null pointer exception for the getResponseCode () method. httpConn is not 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();}

What is the reason for this exception?

+3
source share

Source: https://habr.com/ru/post/1771469/


All Articles