2009年7月27日 星期一

HttpClient 2_post method

b) port method : 看完 get method 後, 其實 post method 大同小異, 差別在於物件不同而已.

public PostDemo {

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

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


取得結果 :

...
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);
}
// 這樣就能將做後續的處理囉...
}
...


其它參數

PostMethod method = new PostMethod(yourUrl);
// add parameters
method.addParameter("parameterName", "parameterValue");
// ... 如果有一個以上

// post image file
Part[] parts = { new StringPart("param1", "我是小胖"),
new StringPart("param2", "體重65"),
new StringPart("param3", "這 2 天變曬黑了"),
new FilePart("personalPic", new File("D:\\小胖照片.jpg")) };

method.setRequestEntity(new MultipartRequestEntity(parts, method
.getParams()));


Post & Get 這 2 個方法應該可以滿足很多需求, 下一篇將介紹其它的 config 如何設定, 如 add header, set timeout, retry handler, multi thread ...等.

0 意見: