2

我想向给定地址发送 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;
}

其中 headers 表示对 (key, value),例如 ("product[title]", "TitleTest")。我尝试通过调用 postMethod(" http://staging.myproject.com.products.xml ", headers, "xxx");来使用该方法 其中标头包括对

("product[title]", "TitleTest"),

(“产品[内容]”,“测试内容”),

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

(“标签”,“aaa,bbb”)

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

有谁知道如何解析地址

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

为了使用上面的方法?哪一部分是url?参数设置是否正确?

谢谢你。

4

2 回答 2

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")
于 2010-01-08T13:32:31.543 回答
1

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

为了设置查询参数,您应该将它们附加到 url,在“?”之后 和 UrlEncoded,如您的示例 url 中所示。

于 2010-01-08T13:27:28.963 回答