我跟着this other SO question设置了网址的参数,但是它给出了错误:
setQueryString(String)
类型中的方法HttpMethodBase
不适用于参数(NameValuePair[])
和
无法实例化类型
NameValuePair
。
我无法理解实际问题。有人可以帮我这个吗?
我从上述问题中使用的代码
GetMethod method = new GetMethod("example.com/page";);
method.setQueryString(new NameValuePair[] {
new NameValuePair("key", "value")
});
答案 0 :(得分:12)
在HttpClient 4.x中,不再有GetMethod
。相反,有HttpGet
。引用tutorial:
查询网址中的参数:
HttpGet httpget = new HttpGet(
"http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");
以编程方式创建查询字符串:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
答案 1 :(得分:1)
无法直接实例化接口,您应该实例化实现此类接口的类。
试试这个:
NameValuePair[] params = new BasicNameValuePair[] {
new BasicNameValuePair("param1", param1),
new BasicNameValuePair("param2", param2),
};
答案 2 :(得分:0)
您可以在网址中传递查询参数。
String uri = "example.com/page?key=value";
HttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(method);
BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String content="", line;
while ((line = br.readLine()) != null) {
content = content + line;
}
System.out.print(content);