2

I'm using the fundamental http request with the same URL. Sometimes it return an entity with length -1. While the response status is OK and the entity is not null.

I run the program for about 10 times, it can work 2 times randomly while the other attempts failed with "Content-type: text/html, lentgh: -1" .

Is there something else I need to set?

HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(textURL.toString());
HttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = response.getEntity();
    System.out.println(entity.getContentType() + ", length: " + entity.getContentLength());
}

1 Answer 1

1

i hit the same question too!i think the content length getting by the method may just get from the header!but sometimes there is no header of content length;if you really want to get the length,you can consume the content yourself.then you can get the length;

public String toString()
{
    InputStream instream=null;
    try{
        instream = this.getContent();
         Charset charset = null;
         if (instream == null) {
                return null;
         }
         int i = (int)this.getContentLength();
         if (i < 0) {
               i = 4096;
         }
         final ContentType contentType = ContentType.get(this);
         if (contentType != null) {
                charset = contentType.getCharset();
         }
         if (charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
         }
         final Reader reader = new InputStreamReader(instream, charset);
         final CharArrayBuffer buffer = new CharArrayBuffer(i);
         final char[] tmp = new char[1024];
         int l;
         int length=0;
         while((l = reader.read(tmp)) != -1) {
               buffer.append(tmp, 0, l);
               length+=l;
         }
         setContentLength(length*2);
         return buffer.toString();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally{
        try {
            instream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return "";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.