【问题标题】:Add query parameters to a GetMethod (using Java commons-httpclient)?将查询参数添加到 GetMethod(使用 Java commons-httpclient)?
【发布时间】:2013-04-20 07:19:30
【问题描述】:

我跟着this other SO question设置了URL参数,但是报错了:

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

无法实例化类型NameValuePair

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

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

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

【问题讨论】:

  • 你把这里多余的分号去掉了吗"example.com/page";
  • 您使用的是 httpclient 3.x 还是 4.x?您给出的示例是典型的 3.x 代码,而不是 4.x。
  • Vikingsteve 在执行代码时已经删除了分号
  • 伟大的 NilsH 我正在使用 4.x.:)。使用 4.x 时如何设置参数?
  • @Anto 确定? 4.x 版本中没有 GetMethod 类。根据 javadoc,它是 HttpGet

标签: java http post get apache-httpclient-4.x


【解决方案1】:

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

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());

【讨论】:

  • 我还应该补充一点,httpclient 4.x 和 httpclient 3.x 有完全不同的 API。您为 httpclient 3.x 找到的示例很可能不适用于 4.x。
  • 我正在尝试将 HTTPclient 4.2.5 与 SalesForce REST API 一起使用,但它不起作用 - 设置参数会导致错误页面,而将“setQueryString”与 3.1 API 一起使用会导致 JSON...任何线索?
【解决方案2】:

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

试试这个:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};

【讨论】:

    【解决方案3】:

    您可以在 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);
    

    【讨论】:

    • 我用过的版本没有GetMethod,请看我提供的cmets
    • 我根据你的httpclient 4.x更改了我的答案
    猜你喜欢
    • 2010-09-18
    • 2012-04-12
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多