2009年7月24日 星期五

HttpClient 1_get method

1. 分享一下最近使用 HttpClient 的心得.
2. HttpClient 可以做很多事情, 這裡不多說, 有興趣的人可以先上官網了解一下.
3. 目前 version 4 尚未正式發怖, 這裡還是使用 3.x 版來做介紹.

request ( get & post)
a) get method : 先看程式如何實作出一個 get 連線:

public GetDemo {

public static void main (String[] args) throws Exception {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod("http://www.google.com.tw");
int httpcode = client.executeMethod(method); // 執行
if (httpcode == HttpStatus.SC_OK) {
System.out.println("連線成功");
} else {
System.out.println("連線失敗");
}

// 用完記得關閉
method.releaseConnection();
}
}


發出去囉...但...我想把結果撈回來看...怎麼寫呢?....其實很簡單...我們在 httpcode == 200 下面加上一段 code :

...
if (httpcode == HttpStatus.SC_OK) {
System.out.println("連線成功");
// 取得結果有幾種方法,
// 1. method.getResponseBodyAsString() , 測試用的話沒關係, 但量大會造成效能不佳, 也不建議使用
// 2. method.getResponseBodyAsStream()
InputStream in = method.getResponseBodyAsStream();

// 自己轉換成 String
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String temp = null;
while ((temp = reader.readLine()) != null) {
result.append(temp);
}
// 這樣就能將做後續的處理囉...
}
...

0 意見: