菜要多喝水才會長大

Tag: Java

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 Comment :, , , more...

Java – 利用 HttpClient 執行 Http 請求

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

網路上有很多 Java 的 Http 相關 Library
這裡選用 HttpClient 的原因是 Google 的 Android 系統裡用的就是 HttpClient
如此一舉兩得,何樂而不為XD

HttpClient是需要另外下載的 Library,首先先到 http://hc.apache.org/下載 HttpClient 和 HttpCore 解開來加到專案中

如此就可以使用 HttpClient 來執行 Http 請求囉,以下為簡單的 HttpGet 範例

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();
    int l;
    byte[] tmp = new byte[2048];
    while ((l = instream.read(tmp)) != -1) {
    }
}

補充:
若是在 compile 的時候 compilier 說找不到 net.jcip.annotations.GuardedBy
到 http://jcip.net/ 下載 jcip-annotation.jar 就可以解決 :D

補充2:
compile 時找不到
org.apache.common.logging
這裡下載 Logging

Leave a Comment :, , , more...

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...