0

Im doing a simple http get,

I see on my result an incomplete response, what Im doing wrong?

here the code:

class GetDocuments extends AsyncTask<URL, Void, Void> {

    @Override
    protected Void doInBackground(URL... urls) {

        Log.d("mensa", "bajando");

             //place proper url 
            connect(urls);

            return null;
    }

    public static void connect(URL[] urls)
    {

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet("http://tiks.document.dev.chocolatecoded.com.au/documents/api/get?type=tree"); 

        // Execute the request
        HttpResponse response;
        try {

            response = httpclient.execute(httpget);



            // Examine the response status
            Log.d("mensa",response.getStatusLine().toString());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                // now you have the string representation of the HTML request

                Log.d("mensa", "estratagema :: "+result);

                JSONObject jObject = new JSONObject(result);

                Log.d("mensa", "resposta jObject::"+jObject);

                Log.d("mensa", "alive 1");

                JSONArray contacts = null;
               contacts = jObject.getJSONArray("success");

               Log.d("mensa", "resposta jObject::"+contacts);

               Log.d("mensa", "alive");

               //instream.close();

            }


        } catch (Exception e) {}
    }



        private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                Log.d("mensa", "linea ::"+line);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

i call it with:

GetDocuments get = new GetDocuments();

       URL url = null;
    try {
        url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    //URL url = new URL("http://www.google.es");

    get.execute(url);

edit 1 I refer to incomplete as the response that gets truncated?

please notice in below image of response how string gets truncated,

is this because of the log size?, but the other problem is that it doesn't parse?

enter image description here

thanks!

manuelBetancurt
  • 15,428
  • 33
  • 118
  • 216
  • Can you be more specify with your INCOMPLETE response. I tried debug your code and JSONException is thrown. 09-23 14:04:42.045: E/a(507): org.json.JSONException: Value true at success of type java.lang.Boolean cannot be converted to JSONArray – edisonthk Sep 23 '13 at 14:05
  • i dont get an exception, also please see edit to check truncated string for response, tnx – manuelBetancurt Sep 23 '13 at 14:11
  • Oh ya, I get the exception because I do some edit on your code. On your GetDocuments class connect method, add log to your exception then you will see it – edisonthk Sep 23 '13 at 14:13
  • you are right thanks, will check this now – manuelBetancurt Sep 23 '13 at 14:17
  • I think you should change "success" to "result" on your getJSONArray. Since you are getting array data not boolean. – edisonthk Sep 23 '13 at 14:22
  • thanks, the problem is before that, even before i ask for the array of any type, the complete string with the received data is truncated' – manuelBetancurt Sep 23 '13 at 14:38
  • Well, I don't know it do help anything to you or not. When I tried copy and paste you code to my eclipse ide, eclipse asked me remove static from connect and convertStreamToString method. – edisonthk Sep 23 '13 at 14:46
  • you sure it was not logcat? I checked this link http://stackoverflow.com/questions/3580062/string-is-being-truncated-when-its-too-long and it said it's logcat's limit to post a lengthy response. – Darpan Jul 29 '15 at 06:28

5 Answers5

2

I don't know if this is going to resolve your problem but you can get rid of your method and use simply:

String responseString = EntityUtils.toString(response.getEntity());
Enrichman
  • 11,157
  • 11
  • 67
  • 101
1

I've had exactly the same issue for the last couple of days. I found that my code worked over WiFi but not 3G. In other words I eliminated all the usual threading candidates. I also found that when I ran the code in the debugger and just waited for (say) 10 seconds after client.execute(...) it worked.

My guess is that

response = httpclient.execute(httpget);

is an asynchronous call in itself and when it's slow returns a partial result... hence JSON deserialization goes wrong.

Instead I tried this version of execute with a callback...

try {
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    String json = httpclient.execute(httpget, responseHandler);         
} finally {
    httpclient.close();
}

And suddenly it all works. If you don't want a string, or want your own code then have a look at the ResponseHandler interface. Hope that helps.

Sam Strachan
  • 525
  • 5
  • 8
1

I have confirmed that this is because size limit of java string. I have checked this by adding the string "abcd" with the ressponse and printed the response string in logcat. But the result is the truncated respose without added string "abcd".

That is

try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
String json = httpclient.execute(httpget, responseHandler);  
json= json+"abcd";
 Log.d("Json ResponseString", json);
} finally {
httpclient.close();
}

So I put an arrayString to collect the response. To make array, I splitted My json format response by using "}"

The code is given below(This is a work around only)

   BasicResponseHandler responseHandler = new BasicResponseHandler();
   String[] array=client.execute(request, responseHandler).split("}");

Then you can parse each objects in to a json object and json array with your custom classes.

If you get any other good method to store response, pls share because i am creating custom method for every different json responses );.

Thank you

Arshad

Arshad
  • 945
  • 9
  • 11
1

Hi Now I am using Gson library to handle the responses.

http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

Thanks Arshad

Arshad
  • 945
  • 9
  • 11
1

I cant' comment directly due to reputation, but in response to https://stackoverflow.com/a/23247290/4830567 I felt I should point out that the size limit of a Java String is about 2GB (Integer.MAX_VALUE) so this wasn't the cause of the truncation here.

According to https://groups.google.com/d/msg/android-developers/g4YkmrFST6A/z8K3vSdgwEkJ it is logcat that has a size limit, which is why appending "abcd" and printing in logcat didn't work. The String itself would have had the appended characters. The previously linked discussion also mentioned that size limits with the HTTP protocol itself can occasionally be a factor, but that most servers and clients handle this constraint internally so as to not expose it to the user.

Community
  • 1
  • 1
Jonathan
  • 176
  • 2
  • 6