Programador Adagal
Programador Adagal

Reputation: 780

Android - Size in chars of an http response

I am not an pro developing android. I wanted to download a JSON object from my server, but only code I could find was this:

    private String downloadUrl(String myurl) throws IOException {
        InputStream is = null;
        // Only display the first 500 characters of the retrieved
        // web page content.
        int len = 500;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            Log.d("ServerConnection", "The response is: " + response);
            is = conn.getInputStream();;
            //is.
            // Convert the InputStream into a string
            String contentAsString = readIt(is, len);
            return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } catch (MalformedURLException e) {
            //
            return "error";
        } catch (IOException e) {
            //
            return "error";
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

And it works fine, I cant understand. But it has a int len = 500, and my returned json is cropped to 500 chars. I tried changing to a great number, but it puts spaces at the end. How can I know the size in chars of the String contained by the InputSteam?

Thanks

Upvotes: 0

Views: 50

Answers (2)

Mina Wissa
Mina Wissa

Reputation: 10971

You can check the Content-Length header value of your response:

Map<String, List<String>> headers = connection.getHeaderFields();
for (Entry<String, List<String>> header : headers.entrySet()) {
if(header.getKey().equals("Content-Legth")){
len=Integer.parseInt(header.getValue());
}
}

or you can your response in a buffered reader like this:

InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
            StringBuilder builder = new StringBuilder();
            int c = 0;
            while ((c = reader.read()) != -1) {
                builder.append((char) c);
            }

Upvotes: 1

Lubos Horacek
Lubos Horacek

Reputation: 1582

Yout can use Apache Commons IO IOUtils.toString to convert InputStream to String or use Gson to read object from input stream directly:

 return gson.fromJson(new InputStreamReader(inputStream), YourType.class);

Upvotes: 0

Related Questions