spring - 如何通过 rest 模板使用表单数据发出 http 请求?

标签 spring httprequest recaptcha multipartform-data resttemplate

我可以使用 postman 执行以下 http 请求: enter image description here 正如你所看到的结果:

{
    "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);

当我在调试中执行以下代码时,我看到以下响应: enter image description here

如您所见,响应包含错误。看起来 responsesecret 没有被服务器接收到。为什么?

我做错了什么?

附言

我用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/

相关文章:

java - 如何将表名添加为 hibernate 模板查询的参数之一

java - Spring MVC 请求太慢

javascript - 是否有可能知道 HTTPRequest 的目标 DOMWindow?

asp.net - "A potentially dangerous Request.Path value was detected from the client"由 GoogleBot 访问时,但不是通过直接链接

javascript - NoRecaptcha 2 和 Opera 12

recaptcha - 在带有假开发域的本地主机上使用 reCAPTCHA

php - 在 g-recaptcha-response 中获取 Null Google 的 reCaptcha

spring - 配置多个 DefaultJmslistenercontainerfactory

java - 部署/托管 Spring Boot 应用程序

php - Android/PHP - JSONParser 无法将网页内容作为 JsonObject 获取