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 18岁简短祝福语经典
11 直播生孩子祝福语简短
12 新年酒席开席祝福语简短
13 夸赞老师祝福语搞笑简短
14 虎年开新车祝福语简短
15 比较简短浪漫的祝福语
16 最搞笑生日祝福语简短
17 送蛇的祝福语简短
18 老哥出门祝福语简短语