将查询参数添加到 GetMethod(使用 Java commons-httpclient)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16230973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add query parameters to a GetMethod (using Java commons-httpclient)?
提问by Java Questions
I followed this other SO questionto set parameter for the URL but it was giving error:
我按照另一个 SO 问题为 URL 设置参数,但它给出了错误:
The method
setQueryString(String)
in the typeHttpMethodBase
is not applicable for the arguments(NameValuePair[])
setQueryString(String)
类型中的方法HttpMethodBase
不适用于参数(NameValuePair[])
and
和
Cannot instantiate the type
NameValuePair
.
无法实例化类型
NameValuePair
。
I am not able to understand the actual problem. Could some one help me on this?
我无法理解实际问题。有人可以帮助我吗?
The code I have used from the above question
我在上述问题中使用的代码
GetMethod method = new GetMethod("example.com/page";);
method.setQueryString(new NameValuePair[] {
new NameValuePair("key", "value")
});
采纳答案by NilsH
In HttpClient 4.x, there is no GetMethod
anymore. Instead there is HttpGet
. Quoting an example from the tutorial:
在 HttpClient 4.x 中,GetMethod
不再有。而是有HttpGet
。引用教程中的一个例子:
Query parameters in the url:
url中的查询参数:
HttpGet httpget = new HttpGet(
"http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");
Creating the query string programatically:
以编程方式创建查询字符串:
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());
回答by Anurag Tripathi
You can pass query parameter within the the url.
您可以在 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);
回答by pancho.gb.cu
Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.
接口不能直接实例化,您应该实例化实现此类接口的类。
Try this:
尝试这个:
NameValuePair[] params = new BasicNameValuePair[] {
new BasicNameValuePair("param1", param1),
new BasicNameValuePair("param2", param2),
};