Kotlin tutorial for integrating Google’s reCAPTCHA on Android
May 22, 2018Kotlin JSON Parser Example for Android
June 10, 2018Google’s reCAPTCHA android example. Integrating captcha in android example on an android app. Android Kotlin tutorial about integrating Google’s safetynet reCAPTCHA in your apps with the tutorial example. Also explained how to validate the token on a server using PHP Rest-API.
First You need to check our kotlin tutorial for Google’s reCAPTCHA example on android-kotlin.
( https://galleonsoft.com/android-kotlin-tutorial-safetynet-recaptcha/ )
You need to replace only Kotlin code with java. so here I’m showing only Java program/Code. First, you need to understand and learn our previous post of Android Kotlin tutorial about integrating Google’s safety net reCAPTCHA in your apps with a tutorial example.
Follow the step of getting SafetyNet Site Key and Secret And Create new android project. and after setup Gradle code you need to set design as well.
After you can see set Kotlin code step It means all done for java android app.
1. Follow this step for Java Android example for integrating Google’s reCAPTCHA.
Create a new class named ApiPostHelper.java This Object/Class for POST API. Also, it helps in others projects. This class required for HttpURLConnection Method. You can use alternatively Volley, Retrofit, etc.
2. Create Java Class ApiPostHelper.java and put the below code.
ApiPostHelper.java package com.galleonsoft.safetynetrecaptcha; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; /** * Author: JIGAR PATEL. * Tutorial_URL: https://galleonsoft.com/tutorial/ */ public class ApiPostHelper { // Send Parameters method public static String SendParams(String reqURL, HashMap<String, String> postDataParams) { URL gsUrl; StringBuilder response = new StringBuilder(); String resultString = ""; try { gsUrl = new URL(reqURL); HttpURLConnection conn = (HttpURLConnection) gsUrl.openConnection(); conn.setReadTimeout(7000); conn.setConnectTimeout(7000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); // For Post encoded Parameters OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); Log.i("responseCode: ", responseCode + ""); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response.append(line); } // convert content stream to a String resultString = response.toString(); } else { resultString = ""; } } catch (Exception e) { e.printStackTrace(); } return resultString; } // Collect Params from HashMap and encode with url. private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> entry : params.entrySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } }
3. Create Android Java AppCompatActivity as reCAPTCHA_Activity.java and put the below code. (It’s your Activity activity class you need to declare in the manifest)
reCAPTCHA_Activity.java package com.galleonsoft.safetynetrecaptcha; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.safetynet.SafetyNet; import com.google.android.gms.safetynet.SafetyNetApi; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class reCAPTCHA_Activity extends AppCompatActivity { private static final String TAG = "reCAPTCHA_Activity"; // TODO: replace the reCAPTCHA KEY with yours private static final String SAFETY_NET_API_KEY = "6LdYZFoUAAAAAAXxuGh0OAnQ_8moTpkzhEtcqARB"; // TODO: replace the SERVER API URL with yours private static final String VERIFY_ON_API_URL_SERVER = "http://apps.galleonsoft.com/api-example/safetynet-recaptcha-verfication.php"; EditText et_message; LinearLayout linearLayoutForm; TextView Tv_Message; Button btn_send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) actionBar.setTitle(getString(R.string.feedback)); et_message = findViewById(R.id.et_message); linearLayoutForm = findViewById(R.id.linearLayoutForm); Tv_Message = findViewById(R.id.Tv_Message); btn_send = findViewById(R.id.btn_send); btn_send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckSafetynetreCAPTCHA(); } }); } public void CheckSafetynetreCAPTCHA() { final String feedback = et_message.getText().toString().trim(); // checking for empty text message if (TextUtils.isEmpty(feedback)) { Toast.makeText(getApplicationContext(), "Enter feedback!", Toast.LENGTH_LONG).show(); return; } // Showing SafetyNet reCAPTCHA dialog SafetyNet.getClient(this).verifyWithRecaptcha(SAFETY_NET_API_KEY) .addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() { @Override public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) { Log.d(TAG, "onSuccess"); if (!response.getTokenResult().isEmpty()) { // Received reCaptcha token and This token still needs to be validated on // the server using the SECRET key api. new verifyTokenFromServer(response.getTokenResult(), feedback).execute(); Log.i(TAG, "onSuccess: " + response.getTokenResult()); } } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof ApiException) { ApiException apiException = (ApiException) e; Log.d(TAG, "SafetyNet Error: " + CommonStatusCodes.getStatusCodeString(apiException.getStatusCode())); } else { Log.d(TAG, "Unknown SafetyNet error: " + e.getMessage()); } } }); } /** * Verifying the captcha token on the server * Server makes call to https://www.google.com/recaptcha/api/siteverify * with SECRET Key and SafetyNet token. */ @SuppressLint("StaticFieldLeak") private class verifyTokenFromServer extends AsyncTask<String, String, String> { String sToken; String msg; public verifyTokenFromServer(String token, String message) { this.sToken = token; this.msg = message; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... args) { // object to hold the information, which is sent to the server HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("recaptcha-response", sToken); // Optional params you can use like this // hashMap.put("feedback-message", msg); // Send the recaptcha response token and receive a Result in return return ApiPostHelper.SendParams(VERIFY_ON_API_URL_SERVER, hashMap); } @Override protected void onPostExecute(String result) { if (result == null) return; Log.i("onPost::: ", result); try { JSONObject jsonObject = new JSONObject(result); boolean success = jsonObject.getBoolean("success"); String message = jsonObject.getString("message"); if (success) { // reCaptcha verified successfully. linearLayoutForm.setVisibility(View.GONE); Tv_Message.setVisibility(View.VISIBLE); } else { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); Log.i("Error: ", e.getMessage()); } } } }
4. ☻ Don’t forget to change SAFETY_NET_API_KEY and VERIFY_ON_API_URL_SERVER on “reCAPTCHA_Activity.kt” Kotlin class file replace the value with yours.
Please follow below link for server verification.
reCAPTCHA Token on Server API
You can download our source code for captcha in android example. If you have any issues, queries or any suggestions please comment at below.
Enjoy the tutorial for Android example about integrating Google’s reCAPTCHA in app. Use this latest tutorial and share it. ?
1 Comment
working source code for captcha in android