2

I am trying to get response data of a Http request. My code looks like this :

public class Networking {

    // private variables
    private URL mUrl;
    private InputStream mInputStream;

    public void Networking() {}

    public InputStream setupConnection(String urlString) {

        // public variables
        int connectionTimeout = 10000; // milliseconds
        int readTimeout = 15000; // milliseconds

        try {
            mUrl = new URL(urlString);

            try {
                // initialize connection
                HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();

                // setup connection
                connection.setConnectTimeout(connectionTimeout);
                connection.setReadTimeout(readTimeout);
                connection.setRequestMethod("GET");
                connection.setDoInput(true);

                // start the query
                try {
                    connection.connect();
                    int response = connection.getResponseCode();

                    if (response == 200) {
                        // OK
                        mInputStream = connection.getInputStream();
                        return mInputStream;

                    } else if (response == 401) {
                        // Unauthorized
                        Log.e("Networking.setupConn...", "unauthorized HttpURL connection");
                    } else {
                        // no response code
                        Log.e("Networking.setupConn...", "could not discern response code");
                    }
                } catch (java.io.IOException e) {
                    Log.e("Networking.setupConn...", "error connecting");
                }


            } catch (java.io.IOException e) {
                Log.e("Networking.setupConn...", "unable to open HTTP Connection");
            }
        } catch (java.net.MalformedURLException e) {
            Log.e("Networking.setupConn..", "malformed url " + urlString);
        }

        // if could not get InputStream
        return null;
    }

    public String getStringFromInputStream() {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder(5000);
        String line;

        try {
            br = new BufferedReader(new InputStreamReader(mInputStream), 512);
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (java.io.IOException e) {
            Log.e("BufferReader(new ..)", e.toString());
            return null;
        } finally {
            if(br != null) {
                try {
                    br.close();
                }catch (java.io.IOException e) {
                    Log.e("br.close", e.toString());
                }
            }
        }
        return sb.toString();
    }
}

The problem is that the getStringFromInputStream function always returns a string that is 4063 bytes long. ALWAYS! No matter what the url.

I checked, and the (line = br.readLine()) part of the code always returns a string of fixed length of 4063.

I don't understand this. Please help.

ironstein
  • 416
  • 8
  • 23
  • what is the content? It appears you are missing the step where you append the line read into the StringBuffer. – Brett Okken Aug 22 '16 at 12:20
  • @BrettOkken that was by mistake (when copy pasting the code in the question). I added the `sb.append(line)` line in. But, the code does not work. – ironstein Aug 22 '16 at 12:24
  • 1
    That would mean that the response is always the same. Why do you find this surprising? What *is* the content? NB `connection.setRequestMethod("GET")` and `connection.setDoInput(true)` merely assert the defaults. They don't do anything useful. And when you get an exception, log the exception. Not some message of your own devising. You will only have to go back later and fix this to debug them, so fix it now. – user207421 Aug 22 '16 at 12:34
  • @EJP it is surprising because I only get partial data, not the complete data. And the partial data is always 4063 characters long. Also, the partial response is different for different URLs, but always 4063 characters long. – ironstein Aug 22 '16 at 12:50

2 Answers2

-1

This my code which works for me:

public String getDataFromUrl(String httpUrlString)
            URL url = new URL(httpUrlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            responseCode = urlConnection.getResponseCode();
            if (responseCode != HttpStatus.SC_OK) {
                    return null;
            } else { // success
                BufferedReader in = null;
                StringBuffer str = new StringBuffer();
                try {
                    in = new BufferedReader(new InputStreamReader(
                            urlConnection.getInputStream()));
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        str.append(inputLine);
                    }
                } finally {
                    if (null != in) {
                        in.close();
                    }
                    urlConnection.disconnect();
                }
                return str.toString();
            }
}
Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
-1

In my opinion, it could be helpful for you if you use a library for http request. I could suggest retrofit or volley.

Besides that, you could just try other methods to get the String from the InputStream, there is an interesting reply for that here

The one that I've used is

BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
    buf.write((byte) result);
    result = bis.read();
}
return buf.toString();
Community
  • 1
  • 1