2013-04-16 26 views
0

我試圖使用httpClient(通過apache)發佈和獲取數據。發佈是絕對正確的,我的代碼沒有問題,但是,我不能說相同的獲取數據。從HTTP響應中提取帖子正文

網站,我想從數據是這樣的:http://www.posttestserver.com/data/2013/04/16/01.13.04594755373

我只希望接收後的主體(即底部的JSON字符串開頭的最近案例),然而,這種方法我我正在使用(以及我在網上找到的每種方法)都會返回時間,源IP,標題和正文(基本上它會返回所有內容)。無論如何解析這個的身體?我不想通過返回的字符串,並告訴它尋找文本「開始郵政正文」,我想要一個自然的方法來做到這一點。這是否存在?

TLDR:我只希望它返回後身體

這裏有什麼是我的代碼:

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

public static void main(String[] args) throws ClientProtocolException, IOException{ 

    HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet("http://www.posttestserver.com/data/2013/04/16/01.41.38521171013"); 
    HttpResponse response = httpclient.execute(httpget); 
    HttpEntity entity = response.getEntity(); 
    System.out.println(EntityUtils.toString(entity)); 

} 

和這裏的返回什麼:

Time: Tue, 16 Apr 13 01:41:38 -0700 
Source ip: 155.198.108.247 

Headers (Some may be inserted by server) 
UNIQUE_ID = UW0OwtBx6hIAACfjfl4AAAAA 
CONTENT_LENGTH = 7627 
CONTENT_TYPE = application/json 
HTTP_HOST = posttestserver.com 
HTTP_CONNECTION = close 
HTTP_USER_AGENT = Apache-HttpClient/4.2.4 (java 1.5) 
REMOTE_ADDR = 155.198.108.247 
REMOTE_PORT = 54779 
GATEWAY_INTERFACE = CGI/1.1 
REQUEST_METHOD = POST 
QUERY_STRING = 
REQUEST_URI = /post.php 
REQUEST_TIME = 1366101698 

No Post Params. 

== Begin post body == 
{"Recent Cases":[{"descript..etc etc"}]} 
== End post body == 

任何想法?

回答

0

你可以發送下面的方法一個url,它會給你一個沒有任何頭部細節的字符串的響應,所以在你的例子只是json。

private static String readUrl(final String urlString) throws Exception { 
     BufferedReader reader = null; 
     try { 
      final URL url = new URL(urlString); 
      reader = new BufferedReader(new InputStreamReader(url.openStream())); 
      final StringBuffer buffer = new StringBuffer(); 
      int read; 
      final char[] chars = new char[1024]; 
      while ((read = reader.read(chars)) != -1) { 
       buffer.append(chars, 0, read); 
      } 
      return buffer.toString(); 
     } finally { 
      if (reader != null) { 
       reader.close(); 
      } 
     } 
    } 
+0

感謝您的快速反應,但你的方法產生完全相同的輸出爲礦(您buffer.toString()產生同我EntityUtils.toString(實體))。 = S。任何其他建議? –

+0

啊,我看到這也是瀏覽器中出現的url的響應,所以它不是整個頁面的實際標題!該響應是無效的JSON。如果他們沒有一個安寧的網址,那麼你解析出的只是產生JSON,你可能會被搞砸,並且必須對String進行解析(這太可怕了)。 – david99world

+0

我將上傳更改爲JSON並具有相同的錯誤,這意味着可能會進行字符串解析。啊。真的希望有一個更優雅的解決方案。無論如何感謝d99w。 –