2012-12-20 69 views
5

我想在Android APP中的服務器上發出HTTPGet請求,但是當我在字符串中更改httpresponse時,該字符串的長度爲0。返回字符串長度爲0的HttpResponse

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":{}} 

有沒有人有一個想法,爲什麼我的字符串是空的?

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

什麼是'localTime'和'timeOffset'?在一個單獨的步驟中構建URL,打印其值,將其粘貼到瀏覽器中,並驗證是否獲得了內容。 – Perception

+3

最近,我注意到一些資源需要一個有意義的用戶代理來防止愚蠢的機器人抓取數據等。 - 這可能是值得試圖欺騙一個IE用戶代理的。 'httpget.setHeader(「User-Agent」,「Mozilla/5.0(Windows; U; MSIE 9.0; Windows NT 9.0; en-US)」);' – jglouie

+0

@Perception我構建它後複製並通過URL,內容回來。 – GermainGum

回答

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。