菜要多喝水才會長大

Java – 使用 HttpClient 的 HttpGet 來取得網頁內容

by GDX on 十二月.10, 2009, under Java, 程式設計

在用 HttpGet 取得網頁內容時使用了以下的程式碼

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity ent = response.getEntity();
if (ent != null) {
   int len;
   char[] tmp = new char[2048];
   BufferedReader br = new BufferedReader(new InputStreamReader(ent.getContent()));
   StringBuffer sb = new StringBuffer();
   while ((len = br.read(tmp)) != -1)
   {
      sb.append(tmp);
   }
}
return sb.toString();

卻發現這樣取得到的內容不完整,將讀取出來的內容存成文字檔觀看後,發現有很多斷點不正確的地方。
於是用 Sniffer 觀看封包內容發現網路傳輸也都正常 ,於是將正常的內容和不正確的內容做了比對;
經過比對後,發現不正確的資訊中有著許多重複的地方。

因此再重回 Debug 模式觀看 len 和 tmp 的內容變化,發現 len 的數值並不是每次都在最大值(2048)
這代表著每次執行 br.read(tmp) 的時候,並不是每次都讀取到 tmp 的最大值
於是將讀取的地方改為

while ((len = br.read(tmp, 0, 2048)) != -1)
{
   sb.append(tmp);
}

結果也是相同,由此可知 br.read(tmp) 並沒有每次都讀取出來 tmp.length 的長度的資料
因此最終改為以下程式碼得以解決:

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity ent = response.getEntity();
if (ent != null) {
   int len;
   char[] tmp = new char[2048];
   BufferedReader br = new BufferedReader(new InputStreamReader(ent.getContent()));
   StringBuffer sb = new StringBuffer();
   while ((len = br.read(tmp)) != -1)
   {
      sb.append(String.valueOf(tmp).substring(0, len));
   }
}
return sb.toString();

如果有更好的解法以及會有這種情況的原因歡迎交流 :-)

:, , ,

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Archives

All entries, chronologically...