要在HTTP GET命令中发送查询字符串信息,您可以使用将简单字符串或NameValuePair对象数组传递到HttpMethod的setQueryString()方法中。我们还需要在将参数值传递给方法之前对其进行编码。
package org.nhooo.example.commons.httpclient; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.util.URIUtil; import org.apache.commons.httpclient.methods.GetMethod; import java.io.IOException; public class SendingQueryParameter { public static void main(String[] args) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("http://localhost:8080/hello.jsp"); try { // 设置查询字符串信息以使用来访问页面 // 简单的字符串信息。 method.setQueryString(URIUtil.encodeQuery("catid=10&page=1")); client.executeMethod(method); // 其他更清洁的替代方法是使用NameValuePair对象来 // 定义HTTP GET方法的参数。 NameValuePair param1 = new NameValuePair("catid", URIUtil.encodeQuery("20")); NameValuePair param2 = new NameValuePair("page", URIUtil.encodeQuery("2")); NameValuePair[] params = new NameValuePair[] {param1, param2}; method.setQueryString(params); client.executeMethod(method); } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); } } }
Maven依赖
<!-- http://repo1.maven.org/maven2/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar --> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>