【问题标题】:How do I add query parameters to a GetMethod (using Java commons-httpclient)?如何将查询参数添加到 GetMethod(使用 Java commons-httpclient)?
【发布时间】:2010-09-18 00:57:45
【问题描述】:

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

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

不过,GetMethod 没有“addParameter”方法。我发现这行得通:

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

但是,我见过的大多数示例要么将参数直接硬编码到 URL 中,例如:

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

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

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

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

【问题讨论】:

    标签: java httpclient getmethod


    【解决方案1】:

    post方法有post参数,但是get methods do not

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

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

    可以在Apache Jakarta Commons page 上找到一个很好的入门教程。

    更新:正如评论中所建议的,NameValuePair 有效。

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

    【讨论】:

    • 我发现这行得通: GetMethod method = new GetMethod("example.com/page"); method.setQueryString(new NameValuePair[] { new NameValuePair("key", "value") }); 这但是,教程页面上没有提到。应该避免这种模式吗?
    • 嗯,显然你不能将代码块放在 cmets 中,所以我编辑了我的问题以添加该示例和其他示例。
    【解决方案2】:

    这不仅仅是个人喜好问题。这里的相关问题是对参数值进行 URL 编码,以便这些值不会被损坏或被误解为额外的分隔符等。

    与往常一样,最好详细阅读 API 文档: HttpClient API Documentation

    阅读本文,您可以看到setQueryString(String) 不会对您的参数和值进行 URL 编码或分隔,而setQueryString(NameValuePair[]) 将自动对您的参数名称和值进行 URL 编码和分隔。这是使用动态数据时最好的方法,因为它可能包含与号、等号等。

    【讨论】:

      【解决方案3】:

      试试这个方法:

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

      【讨论】:

      • UrlBuilder在什么包里?
      • 我觉得应该是:"GetMethod(builder.build())"
      • URIBuilder 位于:org.apache.http.client.utils.URIBuilder;
      • URIBuilder 是 Apache HttpClient 4.5.x 以后的版本。旧版本不走运,可能不得不依赖 method.setQueryString(new nameValuePair[]{ new NameValuePair("theKey", "theValue" });
      猜你喜欢
      • 2013-04-20
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多