2016-09-25 120 views
1

驗證它的時候總是返回false後,我得到令牌g-recaptcha-response的響應,我與驗證碼驗證它是這樣的:驗證碼與谷歌

@Service 
public class RecaptchaService { 

    private static class RecaptchaResponse { 
     @JsonProperty("success") 
     private boolean success; 
     @JsonProperty("error-codes") 
     private Collection<String> errorCodes; 
    } 

    @Value("${recaptcha.url}") 
    private String recaptchaUrl; 

    @Value("${recaptcha.secret-key}") 
    private String recaptchaSecretKey; 


    public boolean isResponseValid(String response) { 

     RestTemplate restTemplate = new RestTemplate(); 

     Map<String, String> params = new HashMap<String, String>(); 
     params.put("secret", recaptchaSecretKey); 
     params.put("response", response); 


     RecaptchaResponse recaptchaResponse = restTemplate.postForEntity(recaptchaUrl, params, RecaptchaResponse.class).getBody(); 

     return recaptchaResponse.success; 

    } 

} 

但我總是得到falserecaptchaResponse.success[missing-input-response, missing-input-secret]error-codes

回答

1

我有同樣的問題,但它是一個簡單的修復。我會解釋這個問題,然後嘗試解釋這個問題。

解決此問題的最簡單方法是將參數追加到URL併爲「對象請求」傳遞一個空值。我已更改您的代碼以演示此更改。

@Service 
public class RecaptchaService { 

    private static class RecaptchaResponse { 
     @JsonProperty("success") 
     private boolean success; 
     @JsonProperty("error-codes") 
     private Collection<String> errorCodes; 
    } 

    @Value("${recaptcha.url}") 
    private String recaptchaUrl; 

    @Value("${recaptcha.secret-key}") 
    private String recaptchaSecretKey; 

    public boolean isResponseValid(String response) { 
     RestTemplate restTemplate = new RestTemplate(); 

     recaptchaUrl = new StringBuilder() 
       .append(recaptchaUrl) 
       .append("?secret=") 
       .append(recaptchaSecretKey) 
       .append("&response=") 
       .append(response) 
       .toString(); 

     RecaptchaResponse recaptchaResponse = restTemplate.postForEntity(recaptchaUrl, null, RecaptchaResponse.class).getBody(); 
     return recaptchaResponse.success; 
    } 
} 

讓我知道這是否適合你。我將參數從Hashmap移動到URL的原因是因爲RestTemplate將Hashmap參數轉換爲JSON格式。 Recaptcha無法理解JSON格式的參數。將參數移動到URL很容易,而且工作。