如何将查询参数添加到GetMethod(使用Java commons-httpclient)? [英] How do I add query parameters to a GetMethod (using Java commons-httpclient)?

查看:272
本文介绍了如何将查询参数添加到GetMethod(使用Java commons-httpclient)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Apache的commons-httpclient for Java,将查询参数添加到GetMethod实例的最佳方法是什么?如果我正在使用PostMethod,它非常简单:

Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward:

PostMethod method = new PostMethod();
method.addParameter("key", "value");

但GetMethod没有addParameter方法。我发现这有效:

GetMethod doesn't have an "addParameter" method, though. I've discovered that this works:

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

然而,我见过的大部分例子都是将参数直接硬编码到URL中,例如:

However, most of the examples I've seen either hard-code the parameters directly into the URL, e.g.:

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

或对查询字符串进行硬编码,例如:

or hard-code the query string, e.g.:

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

这些模式中的一种是首选吗?为什么PostMethod和GetMethod之间的API差异?那些用于其他HttpMethodParams方法的是什么?

Is one of these patterns to be preferred? And why the API discrepancy between PostMethod and GetMethod? And what are all those other HttpMethodParams methods intended to be used for?

推荐答案

Post方法有post参数,但获取方法不要

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

查询参数嵌入在URL中。当前版本的HttpClient接受构造函数中的字符串。如果你想添加上面的键值对,你可以使用:

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

可以在 Apache Jakarta Commons页面

更新:正如评论中所建议的那样,NameValuePair可以工作。

Update: As suggested in the comment, NameValuePair works.

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

这篇关于如何将查询参数添加到GetMethod(使用Java commons-httpclient)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆