Google Recaptcha using Scala Try, Apache HttpClient POST with a Json response

  /**

   * Validate a recaptcha token.

   *  https://developers.google.com/recaptcha

   */

  def validateRecaptcha(token: String, addr: String, secret: String, uri: URI): Boolean = {

 

    val post = new HttpPost

    post.setURI(uri)

    val urlParameters = new ArrayList[NameValuePair]

    urlParameters.add(new BasicNameValuePair(“secret”, secret))

    urlParameters.add(new BasicNameValuePair(“response”, token))

    urlParameters.add(new BasicNameValuePair(“remoteip”, addr))

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

 

    val client = HttpClientBuilder.create.build

    val response = client.execute(post);

    val buffer = Try(new BufferedReader(

      new InputStreamReader(response.getEntity().getContent())))

    // actually quite difficult to read

    buffer match {  

      case Success(b) => {

        try {

          val str = Stream.continually(b.readLine).takeWhile(_ != null).mkString(“\n”)

          val json = new JSONObject(str)

          true

        } catch {

          case ex: Exception => {

            log.error(“ERR_RECAPTCHA_READ_RESPONSE”, ex)

            IOUtils.closeQuietly(b)

            false

          }

        }

      }

      case Failure(e) => {

        log.error(“ERR_RECAPTCHA_CONNECTION”, e)

        false

      }

    }