返回HttpResponse到字符串长度0

时间:2012-12-20 02:13:30

标签: java android

我正在尝试在Android APP中的服务器上发出HTTPGet请求,但是当我更改字符串中的httpresponse时,字符串为0长度。

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://"+server+path+"?assets="+URLEncoder.encode(query, "US-ASCII")+"&lt="+localTime+"&to="+timeOffset);
HttpResponse response = httpclient.execute(httpget);
System.out.println("Status"+ response.getStatusLine());
System.out.println("Length "+org.apache.http.util.EntityUtils.toString(response.getEntity()).length());
return org.apache.http.util.EntityUtils.toString(response.getEntity());

Catlog:

I/System.out(22344): StatusHTTP/1.1 200 OK
I/System.out(21737): Length 0

uri很好,当我在浏览器中复制/浏览它时,我有这样的结果:

{"ads":[{"i"...],"pxs":{}}

有没有人知道我的字符串为空的原因?

Udpate 1:

    long localTime = System.currentTimeMillis();
    Date date = new Date();
    @SuppressWarnings("deprecation")
    int timeOffset = date.getTimezoneOffset ();

更新2:

我添加了这一行:

httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)");

现在我有这个错误:

目录下载

 E/AndroidRuntime(23584): FATAL EXCEPTION: AsyncTask #2
 E/AndroidRuntime(23584): java.lang.RuntimeException: An error occured while executing doInBackground()
 E/AndroidRuntime(23584):   at android.os.AsyncTask$3.done(AsyncTask.java:278)
 E/AndroidRuntime(23584):   at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
 E/AndroidRuntime(23584):   at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
 E/AndroidRuntime(23584):   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
 E/AndroidRuntime(23584):   at java.util.concurrent.FutureTask.run(FutureTask.java:137)
 E/AndroidRuntime(23584):   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
 E/AndroidRuntime(23584):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
 E/AndroidRuntime(23584):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
 E/AndroidRuntime(23584):   at java.lang.Thread.run(Thread.java:864)
 E/AndroidRuntime(23584): Caused by: java.lang.IllegalStateException: Content has been consumed
 E/AndroidRuntime(23584):   at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)

1 个答案:

答案 0 :(得分:3)

System.out.println("Length "+org.apache.http.util.EntityUtils.toString(response.getEntity()).length());
return org.apache.http.util.EntityUtils.toString(response.getEntity());

你正在使用它两次。这就是为什么你得到

java.lang.IllegalStateException: Content has been consumed

尝试将其设置为参考。

            HttpEntity entity = response.getEntity();
            String responseText = EntityUtils.toString(entity);

然后做你对responseText的处理。