views:

52

answers:

2

Hello!

I'm getting a problem making an HTTP POST in Android.

The problem occur when the code is reading the response, it cant obtain the complete web page code I want to retrieve.

I only retrieve a piece of the web.

Here is the code:

    try {

        HttpClient httpclient = new DefaultHttpClient(); 

        HttpPost httppost = new HttpPost(URL);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
        nameValuePairs.add(new BasicNameValuePair("text", "06092010"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

        HttpResponse response; 
        response=httpclient.execute(httppost);

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));


        String  s = "";
        String line = reader.readLine();

        while(line != null){
            s += line+"\n";
            line = reader.readLine();
        }


        Log.d("Street", "Result: "+s);          


    } catch (ClientProtocolException e) { 
        // TODO Auto-generated catch block          
        Log.d("Street", e.toString());   
    } catch (IOException e) { 
        // TODO Auto-generated catch block          
        Log.d("Street", e.toString());
    } catch (Exception e) {
        Log.d("Street", e.toString());
    }
A: 

So reader.readLine is returning null before you have reached the end of the stream? Does the buffer contain a newline at the end? The docs suggest that the end of the stream does not constitute an "end of line":

Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

I use this approach myself, it works, but is not a very efficient solution:

public static String URLToString(URL url) throws IOException {
    InputStream in = (InputStream) url.getContent();
    int ch;

    StringBuffer b = new StringBuffer();
    while( ( ch = in.read() ) != -1 ){
        b.append( (char)ch );
    }

    return b.toString();
}
Gaz Davidson
+1  A: 

Hi Gaz!

Using your code I get the same result, but now I know the problem.

The problem isnt it the code, is the Android LogCat (a Logger) where I print the resulting string. In this logger if the string is too long it only shows a short piece of the result.

So the problem was the way that the logger of android shows the longs strings

Thanks Gaz for the help!

Francisco Javier