1

I followed this other SO question to set parameter for the URL but it was giving error:

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

and

Cannot instantiate the type 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") 
}); 
Community
  • 1
  • 1
Java Questions
  • 7,813
  • 41
  • 118
  • 176

3 Answers3

13

In HttpClient 4.x, there is no GetMethod anymore. Instead there is HttpGet. Quoting an example from the tutorial:

Query parameters in the 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());
NilsH
  • 13,705
  • 4
  • 41
  • 59
  • I should also add that httpclient 4.x and httpclient 3.x have quite different APIs. Examples you find for httpclient 3.x will most likely not work with 4.x. – NilsH Apr 26 '13 at 08:07
  • I am trying to use HTTPclient 4.2.5 with SalesForce REST API and it does not work - setting parameter results in an error page, while using "setQueryString" with 3.1 API results in JSON... Any clues? – Daniil Shevelev Jul 05 '13 at 20:12
1

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),
};
0

You can pass query parameter within the the 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);
Anurag Tripathi
  • 1,208
  • 1
  • 12
  • 31