param_list.cgi CGI脚本只是单的回显接收到的所以参敎ͼ在下面的输出中,你可以看到URIUtil如何对第一个参数进行编码:
With Query String: http://www.discursive.com/cgi-bin/jccook/param_list.cgi?test1=O%20Reilly&blah=Whoop
Response:
These are the parameters I received:
test1:
O Reilly
blah:
Whoop
提示Q你不必在setQueryString()Ҏ中加入?P当HttpClient实例执行executeMethod()ҎӞ它会被自动加入?br />
讨论Q?br /> 在前面的例子中,HttpMethod的setQueryString()Ҏ是一ơ性将整个查询字符串加q去Q但是还有另外一U选择Q通过一个NameValuePair对象的数l来讄查询字符丌Ӏ当一个NameValuePair[]传入setQueryString()Ҏ中时QHttpMethod实例会从数组中取出每一个NameValuePair对象Q然后创Zpd?amp;号分割的参数。这U方法ɽE序代码更加q净Q因Z不必q接字符串来传递多个参数。下面的例子用NameValuePair对象Q与前一个例子设|了同样的参敎ͼ
1 // 用NameValuePair对象讄查询参数
2 HttpMethod method = new GetMethod( url );
3 NameValuePair pair = new NameValuePair( "test1", URIUtil.encodeQuery( "O Reilly" ) );
4NameValuePair pair2 = new NameValuePair( "blah", URIUtil.encodeQuery( "Whoop" ) );
5NameValuePair[] pairs = new NameValuePair[] { pair, pair2 };
6method.setQueryString( pairs );
7System.out.println( "With NameValuePairs: " + method.getURI( ) );
8client.executeMethod( method );
9 System.out.println( "Response:\n " + method.getResponseBodyAsString( ) );
10method.releaseConnection( );
ҎRFC1738QURL只能够包含字母和数字字符Q[0-9,a-z,A-Z]和一些特D字W。如果你需要在参数中传送一些URL所不允许的字符Q你需要对你的字符串进行编码,以符合RFC1738的规定。URIUtilcL一个方法encodeQuery()能够对前面例子中?O Reilly"q行~码。下面的代码展示了用URIUtilcL对包含在URL中的字符串进行编码:
1 String encoded1 = URIUtil.encodeQuery( "<test>=O'Connell" );
2 String encoded2 = URIUtil.encodeQuery( "one:two=thr ee#" );
3
4 String decoded = URIUtil.decode( "Hello%20World%3F" );
5
6 System.out.println( "Encoded: " + encoded1 );
7 System.out.println( "Encoded: " + encoded2 );
8 System.out.println( "Decoded: " + decoded );
q个单的例子用URIUtilcd两个字符串进行了~码Qƈ对一个经q编码的字符串进行解码。下面的输出展示了每个{换的l果Q?br />Encoded: %3ctest%e3=O'Connell
Encoded: one%3atwo=thr%20ee#23
Decoded: Hello World?
参考:
在这个例子中QURLUtil对传入的查询字符串的内容q行了编码。最q,HttpClient组一些URL~码和解码的逻辑代码Ud了Jakarta Commons Codec目中,对应的类名ؓURLCodec。需要URLCodec更多的信息,请参?/span>