PostMethod:如何向给定地址发出请求?

时间:2010-01-08 13:15:05

标签: java apache-commons-httpclient

我想将POST请求添加到给定地址,例如

  

http://staging.myproject.com/products.xml?product[title]=TitleTest&product[content]=TestContent&product[price]=12.3&tags=aaa,bbb

对于POST请求我创建了一个通用方法:

private String postMethod(String url, HashMap<String, String> headers, String encodedAuthorizationString) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(url);
    post.setRequestHeader("Authorization", encodedAuthorizationString);
    if(headers != null && !headers.isEmpty()){
        for(Entry<String, String> entry : headers.entrySet()){
            post.setRequestHeader(new Header(entry.getKey(), entry.getValue()));
        }
    }
    client.executeMethod(post);
    String responseFromPost = post.getResponseBodyAsString();
    post.releaseConnection();
    return responseFromPost;
}

其中标题表示对(键,值),例如(“product [title]”,“TitleTest”)。我试着通过调用来使用该方法 postMethod(“http://staging.myproject.com.products.xml”,header,“xxx”); 标题包括对

  

(“product [title]”,“TitleTest”),

     

(“product [content]”,“TestContent”),

     

(产品[价格],“12.3”),

     

(“tags”,“aaa,bbb”)

但服务器返回了错误消息。

有谁知道如何解析地址

  

http://staging.myproject.com/products.xml?product[title]=TitleTest&product[content]=TestContent&product[price]=12.3&tags=aaa,bbb

为了与上述方法一起使用?哪个部分是网址?参数设置是否正确?

谢谢。

2 个答案:

答案 0 :(得分:3)

我发现了一个问题:

private String postMethod(String url, HashMap<String, String> headers, String encodedAuthorizationString) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(url);
    post.setRequestHeader("Authorization", encodedAuthorizationString);
    if(headers != null && !headers.isEmpty()){
        for(Entry<String, String> entry : headers.entrySet()){
            //post.setRequestHeader(new Header(entry.getKey(), entry.getValue()));
            //in the old code parameters were set as headers (the line above is replaced with the line below)
            post.addParameter(new Header(entry.getKey(), entry.getValue()));
        }
    }
    client.executeMethod(post);
    String responseFromPost = post.getResponseBodyAsString();
    post.releaseConnection();
    return responseFromPost;
}
  

url =   http://staging.myproject.com/products.xml

参数:

  

(“product [title]”,“TitleTest”),

("product[content]", "TestContent"),

(product[price], "12.3"),

("tags", "aaa,bbb")

答案 1 :(得分:1)

您似乎将URL查询参数混淆,例如product [price] = 12.3与HTTP请求标头。使用setRequestHeader()意味着设置HTTP请求标头,这是与任何HTTP请求关联的元数据。

为了设置查询参数,您应该在'?'之后将它们附加到网址和UrlEncoded,如您的示例网址。