Java如何将查询字符串添加到HttpMethod对象?
要在HTTPGET命令中发送查询字符串信息,您可以使用将简单字符串或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对象来
//定义HTTPGET方法的参数。
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>
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志