問題:
??????? 你需要使用HTTP POST 方法來向一個(gè)servlet傳遞參數(shù)。
討論:
??????? 創(chuàng)建一個(gè) PostMethod 對象,然后調(diào)用 setParameter() 或 addParameter() 方法設(shè)置參數(shù)。 PostMethod 對象將會(huì)傳送一個(gè) Content-Type 頭為 application/x-www-form-urlencoded 的請求,并且參數(shù)將在請求body中被傳送。在下列的例子中演示了用 PostMethod 對象傳遞參數(shù)的用法:
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腳本會(huì)對所以接收到的參數(shù)進(jìn)行回顯,從下面的輸出中,你可以看到傳遞給CGI腳本的三個(gè)參數(shù):
These?are?the?parameters?I?received:
test1:
??Hello?World
test2:
??This?is?a?Form?Submission
Blah:
??Whoop
??Whoop2
?????? 有幾種方法來在一個(gè)PostMethod對象中設(shè)置參數(shù)。最直接的方法就是調(diào)用setParameter()方法,并傳遞兩個(gè)字符串給它:參數(shù)的名稱和參數(shù)值。setParameter()方法將會(huì)替代任何已經(jīng)存在的同名參數(shù)。但是,如果一個(gè)同名的參數(shù)已經(jīng)存在一個(gè)PostMethod對象中,addParameter()將會(huì)加入另一個(gè)同名參數(shù)值;addParameter()方法同樣接受兩個(gè)String:參數(shù)名和參數(shù)值。另一種方法,這兩個(gè)方法同樣接受一個(gè)包裝了參數(shù)名和參數(shù)值的NameValuePair對象。在前面的例子中,通過addParameter()方法,用參數(shù)名Blah傳遞了兩個(gè)值,第一次用兩個(gè)String作為參數(shù),第二次用一個(gè)NameValuePair對象作為參數(shù)。