【问题标题】:How make http request using form data by rest template?如何通过rest模板使用表单数据发出http请求?
【发布时间】:2015-03-13 12:24:32
【问题描述】:

我可以使用邮递员执行以下 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);

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

如您所见,响应包含错误。看起来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());

效果很好。

【问题讨论】:

    标签: spring httprequest recaptcha multipartform-data resttemplate


    【解决方案1】:

    我强烈建议使用来自MashapeUnirest.io。它使您有机会简单地创建 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("成功")

    这将为您提供所需的布尔值。

    【讨论】:

    • JSON - 什么类?
    • 哦,对不起,我忘了提。我还建议使用 Google 的 json-simple 工具包来处理 JSON 对象。
    • 链接失效了。
    【解决方案2】:

    这对我有用:

    RecaptchaResponse.java:

    public class RecaptchaResponse {
    
        public boolean success;
    
        @JsonProperty(value = "error-codes")
        public List<String> errorCodes;
    }
    

    LoginController.java:

    /* Spring's MultiValueMap, not Apache's */
    MultiValueMap<String,String> params = new LinkedMultiValueMap<String,String>();
    params.add("secret", "...");
    params.add("response", recaptchaValue);
    
    RecaptchaResponse recaptchaResponse = restTemplate.postForObject("https://www.google.com/recaptcha/api/siteverify", params, RecaptchaResponse.class);
    
    if(recaptchaResponse.success)...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      相关资源
      最近更新 更多