PostMethod:如何向给定地址发出请求?
我想向给定地址重新发送 POST 请求,例如
的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", 标头, “xxx”); 其中标头包含对
(“产品[标题]”,“TitleTest”),
(“产品[内容]”,“测试内容”),
(产品[价格],“12.3”),
(“标签”,“aaa,bbb”)
但是服务器返回错误消息。
有谁知道如何解析地址
中才能按照上面的方法使用吗? url 是哪一部分?参数设置是否正确?
谢谢。
I would like to reate a POST request to a given address, let it for example be
for POST requests I've created an universal method:
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;
}
where headers represents pairs (key, value), for example ("product[title]", "TitleTest"). I tried to use the method by calling
postMethod("http://staging.myproject.com.products.xml", headers, "xxx");
where headers included pairs
("product[title]", "TitleTest"),
("product[content]", "TestContent"),
(product[price], "12.3"),
("tags", "aaa,bbb")
but the server returned an error message.
Does anyone know how to parse the address
in order to use it with the method above? Which part is url? Are parameters set correctly?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现了一个问题:
参数:
I've found a problem:
parameters:
您似乎混淆了 URL 查询参数,例如 Product[price]=12.3 与 HTTP 请求标头。使用 setRequestHeader() 旨在设置 HTTP 请求标头,它们是与任何 HTTP 请求关联的元数据。
为了设置查询参数,您应该将它们附加到 url 的“?”之后和 UrlEncoded,如您的示例 url 中所示。
You seem to be confusing URL query parameters, such as product[price]=12.3 with HTTP request headers. Using setRequestHeader() is meant to set the HTTP request headers, which are meta-data associated with any HTTP request.
In order to set the query parameters, you should append them to the url, after a '?' and UrlEncoded, as in your example url.