我想向给定地址重新发送 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;
}
其中 header 表示对(键、值),例如(“product[title]”、“TitleTest”)。我尝试通过调用来使用该方法 postMethod("http://staging.myproject.com.products.xml ", headers, "xxx"); 其中 header 包含对
("product[title]", "TitleTest"),
("product[content]", "TestContent"),
(product[price], "12.3"),
("tags", "aaa,bbb")
但服务器返回错误消息。
有谁知道如何解析地址
要按照上面的方法使用吗? url 是哪一部分?参数设置是否正确?
谢谢。
最佳答案
我发现一个问题:
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;
}
参数:
("product[title]", "TitleTest"),
("product[content]", "TestContent"), (product[price], "12.3"), ("tags", "aaa,bbb")
关于java - 发布方法 : How to make request to a given address?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2027748/