How do I add query parameters to a GetMethod (using Java commons-httpclient)?

混江龙づ霸主 提交于 2019-11-28 06:46:15
Ryan Guest

Post methods have post parameters, but get methods do not.

Query parameters are embedded in the URL. The current version of HttpClient accepts a string in the constructor. If you wanted to add the key, value pair above, you could use:

String url = "http://www.example.com/page?key=value";
GetMethod method = new GetMethod(url);

A good starting tutorial can be found on the Apache Jakarta Commons page.

Update: As suggested in the comment, NameValuePair works.

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

It's not just a matter of personal preference. The pertinent issue here is URL-encoding your parameter values, so that the values won't get corrupted or misinterpreted as extra delimiters, etc.

As always, it is best to read the API documentation in detail: HttpClient API Documentation

Reading this, you can see that setQueryString(String) will NOT URL-encode or delimit your parameters & values, whereas setQueryString(NameValuePair[]) will automatically URL-encode and delimit your parameter names and values. This is the best method whenever you are using dynamic data, because it might contain ampersands, equal signs, etc.

Randal Harleigh

Try it this way:

    URIBuilder builder = new URIBuilder("https://graph.facebook.com/oauth/access_token")
            .addParameter("client_id", application.getKey())
            .addParameter("client_secret", application.getSecret())
            .addParameter("redirect_uri", callbackURL)
            .addParameter("code", code);

    HttpPost method = new HttpPost(builder.build());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!