5

我正在尝试在 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());

目录:

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

uri 很好,当我在浏览器中复制/粘贴它时,我得到如下结果:

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

有谁知道为什么我的字符串是空的?

更新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)
4

1 回答 1

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 做你必须做的事情。

于 2012-12-20T03:29:49.087 回答