2013-04-26 35 views
0

我跟着this other SO question設置參數的URL,但它給錯誤:將查詢參數添加到GetMethod(使用Java commons-httpclient)?

The method setQueryString(String) in the type HttpMethodBase is not applicable for the arguments (NameValuePair[])

Cannot instantiate the type NameValuePair .

我無法瞭解實際問題。有人能幫我解決這個問題嗎?

我從上面的問題中使用的代碼

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

沒有ü這裏除去多餘的分號' 「example.com/page」;' – vikingsteve 2013-04-26 07:43:22

+1

您正在使用的HttpClient 3.x或4.x的?你給的例子是典型的3.x代碼,而不是4.x. – NilsH 2013-04-26 07:43:55

+0

Vikingsteve在移除代碼時已經移除了這個分號 – 2013-04-26 07:46:05

回答

11

在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()); 
+0

我還應該添加httpclient 4.x和httpclient 3.x有很不相同的API。你發現httpclient 3.x的例子很可能不適用於4.x. – NilsH 2013-04-26 08:07:09

+0

我想使用HTTP客戶端4.2.5與SalesForce REST API,它不起作用 - 設置參數結果在一個錯誤頁面,同時使用「setQueryString」與3.1 API結果在JSON ... 任何線索? – 2013-07-05 20:12:16

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); 
+0

我已經使用的版本中沒有GetMethod,請看看我提供的註釋 – 2013-04-26 07:50:33

+1

我根據您的httpclient 4.x更改了我的答案 – 2013-04-26 10:11:38

1

接口不能直接實例化,你應該實例類實現這樣的接口。

試試這個:

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