Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8528667
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T08:51:15+00:00 2026-06-11T08:51:15+00:00

So in my android app, which uses GET to pull a webpage and download

  • 0

So in my android app, which uses GET to pull a webpage and download the text, I perform:

private InputStream OpenHttpConnection(String urlString) throws IOException {
    Log.d("Networking", "InputStream called");
    InputStream in = null;
    int response = -1;

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

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

        httpConn.setConnectTimeout(10000);
        httpConn.setReadTimeout(10000);
        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) {
            Log.d("Networking", "" + ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
    return in;
}

private String DownloadText(String URL) {
    int BUFFER_SIZE = 2000;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        } 
    catch (IOException e) {
        Log.d("Networking", "" + e.getLocalizedMessage());
        return "";
    }
    InputStreamReader isr = new InputStreamReader(in);
    int charRead;
    String str = "";
    char[] inputBuffer = new char[BUFFER_SIZE];
    try {
        while ((charRead = isr.read(inputBuffer))>0) {
            //---convert the chars to a String---
            String readString = String.copyValueOf(inputBuffer, 0, charRead);
            str += readString;
            inputBuffer = new char[BUFFER_SIZE]; }
        in.close();
    }
    catch (IOException e) {
        Log.d("Networking", "" + e.getLocalizedMessage());
        return "";
    }
    return str;
}

This works perfectly if I call stringx = DownloadText(“http://hello.com/whatever.txt”), as long as whatever.txt exists.

If it 404s, however, it crashes. This surprises me – a 404 is still returning content, surely? I’ve put lots of debug in and it seems to execute the line:

    InputStreamReader isr = new InputStreamReader(in);

Before crashing. Nothing after this line executes. I’ve tried using a try {} catch (IOException) {} around this, but it says the line doesn’t throw the exception.

Does anyone have any insight into why this line is causing such a problem? My application is almost complete, but the error handling is causing me problems!

Many thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T08:51:16+00:00Added an answer on June 11, 2026 at 8:51 am

    This bit of your code:

        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    

    prevents from in being assigned when you get a 404. If you get anything besides an HTTP_OK (200), in will be null and your InputStreamReader assignment will fail.

    To handle this error, you can use the following pattern:

    class HTTPException extends IOException {
        private int responseCode;
    
        public HTTPException( final int responseCode ) {
            super();
            this.responseCode = responseCode;
        }
    
        public int getResponseCode() {
            return this.responseCode;
        }
    }
    

    Then change your code as follows:

    private InputStream OpenHttpConnection(String urlString) throws IOException {
        Log.d("Networking", "InputStream called");
        InputStream in = null;
        int response = -1;
    
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
    
        if(!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
    
            httpConn.setConnectTimeout(10000);
            httpConn.setReadTimeout(10000);
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            } else { // this is new
                throw new HTTPException( response );
            }
    
        }
        catch (Exception ex) {
                Log.d("Networking", "" + ex.getLocalizedMessage());
                throw new IOException("Error connecting");
            }
        return in;
    }
    
    private String DownloadText(String URL) {
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            } 
        catch (IOException e) {
            Log.d("Networking", "" + e.getLocalizedMessage());
            return "";
        }
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];
        try {
            while ((charRead = isr.read(inputBuffer))>0) {
                //---convert the chars to a String---
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE]; }
            in.close();
        }
        catch( HTTPException e ) {
            Log.d( String.format( "HTTP Response not ok: %d", e.getResponseCode() ) );
            // handle whatever else you need to handle here.
        }
        catch (IOException e) {
            Log.d("Networking", "" + e.getLocalizedMessage());
            return "";
        }
        return str;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Problem: I am building Android app in Eclipse which uses shared lib libgstreamer-0.10.so (GStreamer-android
I have an Android app which includes an activity called Help This uses a
I am trying develop an Android app which uses Google maps. So for the
I have an Android app which uses Jackson parser for JSON parsing. After I've
Hi I've an android app which uses an XML file to render its User
I have an Android app which uses a jar library generated from another Eclipse
I'm working on an Android app, which uses bluetooth connection to transfer data between
I am developing an Android app which uses the current user location for result.
I am writing an app which uses android's speech recognition. However my app doesnt
I have an app released on the android market which uses sqlite and displays

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.