1

我按照另一个 SO question为 URL 设置参数,但它给出了错误:

setQueryString(String)类型中的方法HttpMethodBase不适用于参数(NameValuePair[])

无法实例化类型NameValuePair

我无法理解实际问题。有人可以帮助我吗?

我从上述问题中使用的代码

GetMethod method = new GetMethod("example.com/page";); 
method.setQueryString(new NameValuePair[] { 
    new NameValuePair("key", "value") 
}); 
4

3 回答 3

13

在 HttpClient 4.x 中,GetMethod不再存在。取而代之的是HttpGet. 引用教程中的一个例子:

url中的查询参数:

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());
于 2013-04-26T07:52:41.390 回答
1

接口不能直接实例化,您应该实例化实现此类接口的类。

尝试这个:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};
于 2014-07-09T22:50:03.623 回答
0

您可以在 url 中传递查询参数。

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);
于 2013-04-26T07:49:04.853 回答