問題:
??????? 你需要使用HTTP POST 方法來向一個servlet傳遞參數。
討論:
??????? 創建一個 PostMethod 對象,然后調用 setParameter() 或 addParameter() 方法設置參數。 PostMethod 對象將會傳送一個 Content-Type 頭為 application/x-www-form-urlencoded 的請求,并且參數將在請求body中被傳送。在下列的例子中演示了用 PostMethod 對象傳遞參數的用法:
import?org.apache.commons.httpclient.HttpClient;
import?org.apache.commons.httpclient.HttpException;
import?org.apache.commons.httpclient.NameValuePair;
import?org.apache.commons.httpclient.methods.PostMethod;
HttpClient?client?=?new?HttpClient(?);
//?Create?POST?method
String?url?=?"http://www.discursive.com/cgi-bin/jccook/param_list.cgi";
PostMethod?method?=?new?PostMethod(?url?);
//?Set?parameters?on?POST????
method.setParameter(?"test1",?"Hello?World"?);
method.addParameter(?"test2",?"This?is?a?Form?Submission"?);
method.addParameter(?"Blah",?"Whoop"?);
method.addParameter(?new?NameValuePair(?"Blah",?"Whoop2"?)?);
//?Execute?and?print?response
client.executeMethod(?method?);
String?response?=?method.getResponseBodyAsString(?);
System.out.println(?response?);
method.releaseConnection(?);
??????
param_list.cgi CGI腳本會對所以接收到的參數進行回顯,從下面的輸出中,你可以看到傳遞給CGI腳本的三個參數:
These?are?the?parameters?I?received:
test1:
??Hello?World
test2:
??This?is?a?Form?Submission
Blah:
??Whoop
??Whoop2
?????? 有幾種方法來在一個PostMethod對象中設置參數。最直接的方法就是調用setParameter()方法,并傳遞兩個字符串給它:參數的名稱和參數值。setParameter()方法將會替代任何已經存在的同名參數。但是,如果一個同名的參數已經存在一個PostMethod對象中,addParameter()將會加入另一個同名參數值;addParameter()方法同樣接受兩個String:參數名和參數值。另一種方法,這兩個方法同樣接受一個包裝了參數名和參數值的NameValuePair對象。在前面的例子中,通過addParameter()方法,用參數名Blah傳遞了兩個值,第一次用兩個String作為參數,第二次用一個NameValuePair對象作為參數。