我可以使用 postman 执行以下 http 请求: 正如你所看到的结果:
{
"succes":false
}
现在我需要使用 restTemplate 执行相同的请求。
为了实现它,我编写了以下代码:
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("secret", "6Le8YwMTAAAAADTIDNBvjxg-x83jt5QvPN-dFGWs");
map.add("response", recapchaResponse);
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> entity = new HttpEntity<Map>(map, headers);
restTemplate.exchange("https://www.google.com/recaptcha/api/siteverify", HttpMethod.POST, entity,ReCaptchaResponse.class);
当我在调试中执行以下代码时,我看到以下响应:
如您所见,响应包含错误。看起来 response
和 secret
没有被服务器接收到。为什么?
我做错了什么?
附言
我用httpClient写过模拟
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("https://www.google.com/recaptcha/api/siteverify");
postMethod.setParameter("secret", "6Le8YwMTAAAAADTIDNBvjxg-x83jt5QvPN-dFGWs");
postMethod.setParameter("response", recapchaResponse);
client.executeMethod(postMethod);
String responseFromServer = new String(postMethod.getResponseBody());
效果不错。
最佳答案
我强烈推荐使用 Unirest.io来自 Mashape .它使您有机会简单地创建 POST 请求:
Unirest.post("http://link.to/rest").field("secret", "xxx").field("response", "xxx").asJsonAsync(new Callback<JsonNode>() {
@Override
public void completed(HttpResponse<JsonNode> httpResponse) {
String response = httpResponse.getBody().toString();
JSONObject responseDictionary = JSON.jsonToDictionary(response);
}
@Override
public void failed(UnirestException e) {
}
@Override
public void cancelled() {
}
});
这将为给定站点创建一个 POST 请求,并返回一个包含响应的 JSON 对象。
responseDictionary.get("success")
这将为您提供所需的 bool 值。
关于spring - 如何通过 rest 模板使用表单数据发出 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29032193/