> This page is for Applications Protection.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.humansecurity.com/llms.txt.

# Native (basic implementation)

> **Note**
>
> This guide is relevant for the current Mobile SDK. While we highly recommend using the latest version, if you are using a legacy integration, refer to the [iOS](/applications/ios-how-to-integrate-the-sdk-in-your-application-v3) or [Android](/applications/android-how-to-integrate-the-sdk-in-your-application-v3) documentation.

After you [add the SDK to your project](/applications/sdk/v5/getting-started), you need to start the SDK and integrate with Bot Defender, Account Defender, or both. You can learn how to do so with this guide.

This guide covers the basic implementation for native apps. If you need another implementation method, see our other guides:

#### Choosing the right implementation

<table>
  <thead>
    <tr>
      <th>Implementation</th>

      <th>Details</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>
        [Native (recommended implementation](./native-easiest-implementation)
      </td>

      <td>
        * Fast integration with minimal points.
        * SDK intercepts your URL requests.
        * Handles blocked requests.
        * **Not recommended** if you need to retry requests after solving challenges.
        * **Not recommended** if you use advanced `URLSession` features (authentication challenges, caching, etc.).
      </td>
    </tr>

    <tr>
      <td>
        [Native (basic implementation)](./native-basic-implementation)
      </td>

      <td>
        * Few integration points.
        * SDK **does not** intercept URL requests.
        * Handles blocked requests.
        * Notifies when a challenge is solved or cancelled; great for analytics and logs.
        * **Not recommended** for retrying requests after challenges.
        * **Not recommended** as a trigger for resending URL requests.
      </td>
    </tr>

    <tr>
      <td>
        [Native (advanced functionality)](./native-advanced-functionality)
      </td>

      <td>
        * SDK intercepts URL requests.
        * Handles blocked requests with challenge results (solved/canceled); great for analytics, logs, and resending URL requests.
        * Option to automatically retry blocked requests after challenges.
        * **Recommended** if you need to retry requests after challenges.
        * **Not recommended** if you use advanced `URLSession` features.
      </td>
    </tr>
  </tbody>
</table>

#### [Recommended implementation](/applications/sdk/v5/native-easiest-implementation)

The recommended implementation for native apps.

#### [Advanced implementation](/applications/sdk/v5/native-advanced-functionality)

The advanced implementation for native apps.

## Prerequisites

* Admin access to the HUMAN **Console**, which you'll need to:
  * Retrieve your **Application ID**. You can find this by navigating to **Platform Settings > Applications** and copying the ID. If you need to use multiple IDs, see [Handle multiple Application IDs](./getting-started#handle-multiple-application-ids).
  * Set the token expiration and validity.
* An integrated HUMAN Enforcer that is enabled and in **active blocking** mode. Refer to our [Enforcer guides](/applications/about-enforcers) for more information.
* **Android:** This article assumes that your app uses [OkHttp](https://square.github.io/okhttp/) or [Ktor](https://ktor.io/), which support [Interceptors](https://square.github.io/okhttp/features/interceptors/). We recommend creating a custom Interceptor particularly for [integrating with Bot Defender](#integrate-with-bot-defender), but you may use any HTTP client of your choice and implement the same logic if needed.

## Start the SDK

When starting the SDK, keep the following in mind:

1. **Start the SDK as soon as possible** in your app's flow. We recommend doing so in the `Application`'s `onCreate` function in Android or the `AppDelegate`'s `didFinishLaunchingWithOptions` function in iOS. If you don't do this, then your application may send a URL request to your server before the SDK starts. This means the request will not include HTTP headers that indicate whether the request is legitimate, and as a result:
   * The **Enforcer** may block the request instead, and
   * The SDK will not be able to present a challenge to the user
2. Start the SDK on the **main thread**.

Below are example implementations for both Android and iOS:

> **Note**
>
> Don't forget to replace `<APP_ID>` with your actual **Application ID**.

#### Android

```kotlin
import android.app.Application
import com.humansecurity.mobile_sdk.HumanSecurity
import com.humansecurity.mobile_sdk.main.policy.HSPolicy
import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType

class MainApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        startHumanSDK()
    }

    private fun startHumanSDK() {
        try {
            val policy = HSPolicy().apply {
                automaticInterceptorPolicy.interceptorType = HSAutomaticInterceptorType.NONE
            }

            HumanSecurity.start(this, "<APP_ID>", policy)
        } catch (exception: Exception) {
            println("Exception: ${exception.message}")
        }
    }
}
```

```java
import android.app.Application;
import android.util.Log;
import com.humansecurity.mobile_sdk.HumanSecurity;
import com.humansecurity.mobile_sdk.main.policy.HSPolicy;
import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType;

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        startHumanSDK();
    }

    void startHumanSDK() {
        try {
            HSPolicy policy = new HSPolicy();
            policy.getAutomaticInterceptorPolicy().setInterceptorType(HSAutomaticInterceptorType.NONE);

            HumanSecurity.INSTANCE.start(this, "<APP_ID>", policy);
        } catch (Exception exception) {
            Log.e("MainApplication", "Error: " + exception.getMessage());
        }
    }
}
```

#### iOS

> **Note**
>
> The Automatic Interception uses `URLSessionConfiguration.default`. If your app uses a custom configuration, set it in the policy using `HSAutomaticInterceptorPolicy.urlSessionConfiguration`.

```swift
import UIKit
import HUMAN

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        startHumanSDK()
        return true
    }

    func startHumanSDK() {
        do {
            let policy = HSPolicy()
            policy.automaticInterceptorPolicy.interceptorType = .none

            try HumanSecurity.start(appId: "<APP_ID>", policy: policy)
        } catch {
            print("Error: \(error)")
        }
    }
}
```

**`Objective-C`**

```c title="Objective-C"
@import HUMAN;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self startHumanSDK];
    return YES;
}

- (void)startHumanSDK {
    HSPolicy *policy = [[HSPolicy alloc] init];
    policy.automaticInterceptorPolicy.interceptorType = HSAutomaticInterceptorTypeNone;

    NSError *error = nil;
    [HumanSecurity startWithAppId:@"<APP_ID>" policy:policy error:&error];
    if (error != nil) {
        NSLog(@"Error: %@", error);
    }
}

@end
```

In particular, note the following:

1. **Initialization:** We start the SDK as early as possible on the main thread to ensure all URL requests include the necessary HTTP headers.
2. **Policy Configuration:** We create an `HSPolicy` instance to configure the SDK's behavior. In this case, we set the `automaticInterceptorPolicy.interceptorType` to `HSAutomaticInterceptorType.NONE` to disable automatic interception of URL requests.
3. **Starting the SDK:** We call the `HumanSecurity.start(appId:policy:)` function with the following parameters:
   * The `Application` instance (Android only)
   * Your

     Application ID

     . If you have multiple IDs, see our [guide](/applications/sdk/v5/getting-started#handle-multiple-application-ids) on how to handle them.
   * The `HSPolicy` object that we configured

## Integrate with Bot Defender

#### Send your requests through the SDK and check for a blocked request

1. Your application adds the SDK's HTTP headers to the URL request with `headersForURLRequest`. Include them on **every** request, and do **not** cache them. They contain a token with an expiration date, and the SDK keeps that token up to date.
2. Your application sends the URL request using your configured HTTP client.
3. If Bot Defender blocks the request, pass the response to `handleBlockResponse`. The SDK presents a challenge to the user.
4. While the SDK is presenting that challenge, `handleBlockResponse` returns a boolean to your request handler.
5. On Android, when that boolean is `true`, replace the response body with `errorBody` for `REQUEST_WAS_BLOCKED` and confirm the block with `errorType`. On iOS, the boolean confirms the request was blocked.

Below are example implementations for both Android and iOS:

#### Android

**`Kotlin`**

```kotlin title="Kotlin"
import com.humansecurity.mobile_sdk.HumanSecurity
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

class BotDefenderInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val newRequest = chain.request().newBuilder()
        val humanHttpHeaders = HumanSecurity.BD.headersForURLRequest("<APP_ID>")
        for ((key, value) in humanHttpHeaders) {
            newRequest.header(key, value)
        }
        val response = chain.proceed(newRequest.build())
        if (!response.isSuccessful) {
            response.body?.string()?.let { responseString ->
                val isHandled = HumanSecurity.BD.handleBlockResponse(responseString, chain.request().url.toString()) { result ->
                    println("Challenge result = $result")
                }
                if (isHandled) {
                    println("Blocked response was handled by the SDK")
                    return response.newBuilder()
                        .body(HumanSecurity.BD.errorBody(HSBotDefenderErrorType.REQUEST_WAS_BLOCKED).toResponseBody())
                        .build()
                }
            }
        }
        return response
    }
}
```

**`Kotlin (OkHttp)`**

```kotlin title="Kotlin (OkHttp)"
import com.humansecurity.mobile_sdk.HumanSecurity
import com.humansecurity.mobile_sdk.main.HSBotDefenderErrorType
import okhttp3.OkHttpClient
import okhttp3.Request

class MyHttpClient {

    private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
        .addInterceptor(BotDefenderInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
        .build()

    fun sendRequest(url: String) {
        try {
            val request: Request = Request.Builder().url(url).build()
            okHttpClient.newCall(request).execute().use { response ->
                if (!response.isSuccessful) {
                    response.body?.string()?.let { responseBody ->
                        when (HumanSecurity.BD.errorType(responseBody)) {
                            HSBotDefenderErrorType.REQUEST_WAS_BLOCKED -> {
                                println("Request was blocked")
                            }
                            else -> {
                                println("Unknown error")
                            }
                        }
                    }
                }
            }
        } catch (exception: Exception) {
            println("Request failed. Exception: $exception")
        }
    }
}
```

**`Kotlin (Ktor)`**

```kotlin title="Kotlin (Ktor)"
import com.humansecurity.mobile_sdk.HumanSecurity
import io.ktor.client.*
import io.ktor.client.call.body
import io.ktor.client.engine.okhttp.*
import io.ktor.client.request.*
import io.ktor.client.statement.*

class MyHttpClient {

    private val httpClient: HttpClient = HttpClient(OkHttp) {
        engine {
            addInterceptor(BotDefenderInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
        }
    }

    suspend fun sendRequest(url: String) {
        try {
            val response: HttpResponse = httpClient.request(url) {}
            val responseBody = response.body<String>()
            when (HumanSecurity.BD.errorType(responseBody)) {
                HSBotDefenderErrorType.REQUEST_WAS_BLOCKED -> {
                    println("Request was blocked")
                }
                else -> {
                    println("Unknown error")
                }
            }
        } catch (exception: Exception) {
            println("Request failed. Exception: $exception")
        }
    }
}
```

**`Java (OkHttp)`**

```java title="Java (OkHttp)"
import com.humansecurity.mobile_sdk.HumanSecurity;
import com.humansecurity.mobile_sdk.main.HSBotDefenderErrorType;
import java.util.HashMap;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.MediaType;

public class BotDefenderInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder newRequest = chain.request().newBuilder();
        HashMap<String, String> humanHttpHeaders = HumanSecurity.INSTANCE.getBD().headersForURLRequest("<APP_ID>");
        for (HashMap.Entry<String, String> entry : humanHttpHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            newRequest.header(key, value);
        }
        Response response = chain.proceed(newRequest.build());
        if (!response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                boolean didHandleBlockResponse = HumanSecurity.INSTANCE.getBD().handleBlockResponse(responseString, chain.request().url().toString(), result -> {
                    Log.i("BotDefenderInterceptor", "Challenge result = " + result);
                    return null;
                });
                if (didHandleBlockResponse) {
                    Log.i("BotDefenderInterceptor", "Blocked response was handled by the SDK");
                    return response.newBuilder()
                        .body(ResponseBody.create(HumanSecurity.INSTANCE.getBD().errorBody(HSBotDefenderErrorType.REQUEST_WAS_BLOCKED), MediaType.parse("application/json")))
                        .build();
                }
            }
        }
        return response;
    }
}
```

**`Java (OkHttp)`**

```java title="Java (OkHttp)"
import com.humansecurity.mobile_sdk.HumanSecurity;
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MyHttpClient {

    private final OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new BotDefenderInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
            .build();

    void sendRequest(String url) {
        Runnable r = () -> {
            try {
                Request request = new Request.Builder().url(url).build();
                Response response = httpClient.newCall(request).execute();
                ResponseBody responseBody = response.body();
                String responseString = null;
                if (responseBody != null) {
                    responseString = responseBody.string();
                    response.close();
                }
                if (!response.isSuccessful() && responseString != null) {
                    switch (HumanSecurity.INSTANCE.getBD().errorType(responseString)) {
                        case REQUEST_WAS_BLOCKED:
                            Log.i("MyHttpClient", "Request was blocked");
                            break;
                        default:
                            Log.i("MyHttpClient", "Unknown error");
                            break;
                    }
                }
            } catch (Exception exception) {
                Log.i("MyHttpClient", "Request failed. Exception: " + exception);
            }
        };
        new Thread(r).start();
    }
}
```

#### iOS

**`Swift (URLSession)`**

```swift title="Swift (URLSession)"
import HUMAN

class MyHttpClient {

    func sendUrlRequest(url: URL) {
        var request = URLRequest(url: url)
        let myHttpHeaders = [String: String]()

        // Configure your request and HTTP headers...

        let humanHttpHeaders = HumanSecurity.BD.headersForURLRequest(forAppId: "<APP_ID>")
        request.allHTTPHeaderFields = myHttpHeaders.merging(humanHttpHeaders) { $1 }

        let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
            if let data {
                let isHandled = HumanSecurity.BD.handleBlockResponse(data: data, url: url.absoluteString) { result in
                    print("Challenge result = \(result)")
                }
                if isHandled {
                    print("Blocked response was handled by the SDK")
                }
            }
        }
        dataTask.resume()
    }
}
```

**`Objective-C (URLSession)`**

```c title="Objective-C (URLSession)"
@import HUMAN;

@implementation MyHttpClient

- (void)sendUrlRequest:(NSURL *)url {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSMutableDictionary<NSString *, NSString *> *myHttpHeaders = [[NSMutableDictionary alloc] init];

    // Configure your request and HTTP headers...

    NSDictionary<NSString *, NSString *> *humanHttpHeaders = [HumanSecurity.BD headersForURLRequestForAppId:@"<APP_ID>"];
    NSMutableDictionary<NSString *, NSString *> *allHTTPHeaderFields = [[NSMutableDictionary alloc] init];
    [allHTTPHeaderFields addEntriesFromDictionary:myHttpHeaders];
    [allHTTPHeaderFields addEntriesFromDictionary:humanHttpHeaders];
    request.allHTTPHeaderFields = allHTTPHeaderFields;

    NSURLSessionDataTask *dataTask = [NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data != nil) {
            BOOL isHandled = [HumanSecurity.BD handleBlockResponseWithData:data url:url.absoluteString callback:^(enum HSBotDefenderChallengeResult result) {
                NSLog(@"Challenge result = %ld", (long)result);
            }];
            if (isHandled) {
                NSLog(@"Blocked response was handled by the SDK");
            }
        }
    }];
    [dataTask resume];
}

@end
```

**`Swift (Alamofire)`**

```swift title="Swift (Alamofire)"
import Alamofire
import HUMAN

class MyHttpClient {

    func sendUrlRequest(url: URL) {
        var myHttpHeaders = [String: String]()

        // Configure your HTTP headers...

        let humanHttpHeaders = HumanSecurity.BD.headersForURLRequest(forAppId: "<APP_ID>")
        let allHTTPHeaderFields = myHttpHeaders.merging(humanHttpHeaders) { $1 }

        AF.request(url, headers: HTTPHeaders(allHTTPHeaderFields)).response { response in
            if let data = response.data {
                let isHandled = HumanSecurity.BD.handleBlockResponse(data: data, url: url.absoluteString) { result in
                    print("Challenge result = \(result)")
                }
                if isHandled {
                    print("Blocked response was handled by the SDK")
                }
            }
        }
    }
}
```

#### Handle blocked requests in your app

When the **Enforcer** blocks a request, it returns a JSON string in the response body with an HTTP status code of `403`, which includes metadata for the SDK. For example:

```json
{
    "vid": "928d7ab3-9cf1-11ee-a624-b802520f369f",
    "appId": "PXj9y4Q8Em",
    "action": "captcha",
    "collectorUrl": "https://collector-pxj9y4q8em.perimeterx.net"
}
```

Your app should pass the entire JSON response to the SDK via the `HSBotDefender/handleBlockResponse` function. If not, the SDK won't present a challenge to the user. When handling blocked requests:

* **Treat blocked requests as a failure.** However, if the user solves or cancels the challenge presented by the SDK, your application's interface will be shown again. In those cases, you may need to indicate to the user that they can continue to interact with your application normally. For example, if the user was attempting to access a certain page before the challenge, then when they return to that same page after solving the challenge, you may want to show a message indicating that they can now continue on to that page.
* **Use the handler callback** to log analytics, create logs, and so on.
* **(Optional) Use the handler callback** to retry the original request when appropriate. Consider the following:
  * **Callback scope:** The callback is called outside the original request's scope. Ensure your app handles this correctly.
  * **Challenge cancellation:** If the challenge is canceled by the user. Do not retry the request to avoid it being blocked again.
  * **Retry block possibility:** The retry attempt may also be blocked. Do not assume it will succeed.

#### Set custom parameters (optional)

[Custom parameters](/applications/set-custom-parameters) are additional custom values that you can set yourself to enrich the data you receive from HUMAN. You can have up to 10 custom parameters, and they must follow the pattern `custom_paramN`, where `N` is a number between 1 and 10. To set custom parameters:

* **Android:** Use a `HashMap<String, String>`
* **iOS:** Use a `Dictionary<String, String>`

Call `HSBotDefender.setCustomParameters(parameters:forAppId:)` only **after** the `HumanSecurity.start(appId:policy:)` function has been called.

Below are example implementations for both Android and iOS:

#### Android

```kotlin
import com.humansecurity.mobile_sdk.HumanSecurity

fun setCustomParametersForBotDefender() {
    try {
        val customParameters = HashMap<String, String>().apply {
            put("custom_param1", "hello")
            put("custom_param2", "world")
        }
        HumanSecurity.BD.setCustomParameters(customParameters, "<APP_ID>")
    } catch (exception: Exception) {
        println("Exception: ${exception.message}")
    }
}
```

```java
import com.humansecurity.mobile_sdk.HumanSecurity;
import java.util.HashMap;
import android.util.Log;

void setCustomParametersForBotDefender() {
    try {
        HashMap<String, String> customParameters = new HashMap<>();
        customParameters.put("custom_param1", "hello");
        customParameters.put("custom_param2", "world");
        HumanSecurity.INSTANCE.getBD().setCustomParameters(customParameters, "<APP_ID>");
    } catch(Exception exception) {
        Log.e("MainApplication", "Exception: " + exception.getMessage());
    }
}
```

#### iOS

```swift
import HUMAN

func setCustomParametersForBotDefender() {
    do {
        let customParameters: [String: String] = [
            "custom_param1": "hello",
            "custom_param2": "world"
        ]
        try HumanSecurity.BD.setCustomParameters(parameters: customParameters, forAppId: "<APP_ID>")
    } catch {
        print("Error: \(error)")
    }
}
```

**`Objective-C`**

```c title="Objective-C"
@import HUMAN;

- (void)setCustomParametersForBotDefender {
    NSMutableDictionary<NSString *, NSString *> *customParameters = [[NSMutableDictionary alloc] init];
    customParameters[@"custom_param1"] = @"hello";
    customParameters[@"custom_param2"] = @"world";

    NSError *error = nil;
    [HumanSecurity.BD setCustomParametersWithParameters:customParameters forAppId:@"<APP_ID>" error:&error];
    if (error != nil) {
        NSLog(@"Error: %@", error);
    }
}
```

## Integrate with Account Defender

#### Enable Account Defender in your app

To enable Account Defender, set the `UserID` of your current logged-in user in the SDK. Below are example implementations for both Android and iOS:

#### Android

```kotlin
import com.humansecurity.mobile_sdk.HumanSecurity

fun onUserLoggedIn(userID: String) {
    try {
        HumanSecurity.AD.setUserId(userID, "<APP_ID>")
    } catch (exception: Exception) {
        println("Exception: ${exception.message}")
    }
}
```

```java
import com.humansecurity.mobile_sdk.HumanSecurity;
import android.util.Log;

void onUserLoggedIn(String userID) {
    try {
        HumanSecurity.INSTANCE.getAD().setUserId(userID, "<APP_ID>");
    } catch(Exception exception) {
        Log.e("MainApplication", "Exception: " + exception.getMessage());
    }
}
```

#### iOS

```swift
import HUMAN

func onUserLoggedIn(userID: String) {
    do {
        try HumanSecurity.AD.setUserId(userId: userID, forAppId: "<APP_ID>")
    } catch {
        print("Error: \(error)")
    }
}
```

**`Objective-C`**

```c title="Objective-C"
@import HUMAN;

- (void)onUserLoggedIn:(NSString *)userID {
    NSError *error = nil;
    [HumanSecurity.AD setUserIdWithUserId:userID forAppId:@"<APP_ID>" error:&error];
    if (error != nil) {
        NSLog(@"Error: %@", error);
    }
}
```

#### Notify HUMAN's backend on outgoing URL requests from the app

For Account Defender to protect the user's account, your app has to provide the SDK with outgoing URL requests.

#### Android

```kotlin
import com.humansecurity.mobile_sdk.HumanSecurity
import okhttp3.Interceptor
import okhttp3.Response

class AccountDefenderInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        try {
            HumanSecurity.AD.registerOutgoingUrlRequest(request.url.toString(), "<APP_ID>")
        } catch (exception: Exception) {
            println("Exception: ${exception.message}")
        }
        return chain.proceed(request)
    }
}
```

**`Kotlin (OkHttp)`**

```kotlin title="Kotlin (OkHttp)"
import okhttp3.OkHttpClient
import okhttp3.Request

class MyHttpClient {

    private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
        .addInterceptor(AccountDefenderInterceptor())
        .build()

    fun sendRequest(url: String) {
        try {
            val request: Request = Request.Builder().url(url).build()
            okHttpClient.newCall(request).execute().use { response ->
                // Handle the response...
            }
        } catch (exception: Exception) {
            println("Request failed. Exception: $exception")
        }
    }
}
```

**`Kotlin (Ktor)`**

```kotlin title="Kotlin (Ktor)"
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.request.*
import io.ktor.client.statement.*

class MyHttpClient {

    private val httpClient: HttpClient = HttpClient(OkHttp) {
        engine {
            addInterceptor(AccountDefenderInterceptor())
        }
    }

    suspend fun sendRequest(url: String) {
        try {
            val response: HttpResponse = httpClient.request(url) {}
            // Handle the response...
        } catch (exception: Exception) {
            println("Request failed. Exception: $exception")
        }
    }
}
```

```java
import com.humansecurity.mobile_sdk.HumanSecurity;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class AccountDefenderInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        try {
            HumanSecurity.INSTANCE.getAD().registerOutgoingUrlRequest(request.url().toString(), "<APP_ID>");
        } catch (Exception exception) {
            Log.i("AccountDefenderInterceptor", "Exception: " + exception.getMessage());
        }
        return chain.proceed(request);
    }
}
```

**`Java (OkHttp)`**

```java title="Java (OkHttp)"
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyHttpClient {

    private final OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new AccountDefenderInterceptor())
            .build();

    void sendRequest(String url) {
        Runnable r = () -> {
            try {
                Request request = new Request.Builder().url(url).build();
                Response response = httpClient.newCall(request).execute();
                // Handle the response...
            } catch (Exception exception) {
                Log.i("MyHttpClient", "Request failed. Exception: " + exception);
            }
        };
        new Thread(r).start();
    }
}
```

#### iOS

```swift
import HUMAN

class MyHttpClient {

    func sendUrlRequest(url: URL) {
        do {
            try HumanSecurity.AD.registerOutgoingUrlRequest(url: url.absoluteString, forAppId: "<APP_ID>")
        } catch {
            print("Error: \(error)")
        }

        // Send the request...
    }
}
```

**`Objective-C`**

```c title="Objective-C"
@import HUMAN;

@implementation MyHttpClient

- (void)sendUrlRequest:(NSURL *)url {
    NSError *error = nil;
    [HumanSecurity.AD registerOutgoingUrlRequestWithUrl:url.absoluteString forAppId:@"<APP_ID>" error:&error];
    if (error != nil) {
        NSLog(@"Error: %@", error);
    }

    // Send the request...
}

@end
```

#### Set additional data (optional)

You can configure HUMAN's backend with additional parameters by setting additional data.

* **Android:** Use a `HashMap<String, String>`.
* **iOS:** Use a `Dictionary<String, String>`.

Call the `HSAccountDefender.setAdditionalData(parameters:forAppId:)` function only **after** the `HumanSecurity.start(appId:policy:)` function has been called.

Below are example implementations for both Android and iOS:

#### Android

```kotlin
import com.humansecurity.mobile_sdk.HumanSecurity

fun setAdditionalDataForAccountDefender() {
    try {
        val additionalData = HashMap<String, String>().apply {
            put("my_key1", "hello")
            put("my_key2", "world")
        }
        HumanSecurity.AD.setAdditionalData(additionalData, "<APP_ID>")
    } catch (exception: Exception) {
        println("Exception: ${exception.message}")
    }
}
```

```java
import com.humansecurity.mobile_sdk.HumanSecurity;
import java.util.HashMap;
import android.util.Log;

void setAdditionalDataForAccountDefender() {
    try {
        HashMap<String, String> additionalData = new HashMap<>();
        additionalData.put("my_key1", "hello");
        additionalData.put("my_key2", "world");
        HumanSecurity.INSTANCE.getAD().setAdditionalData(additionalData, "<APP_ID>");
    } catch(Exception exception) {
        Log.e("MainApplication", "Exception: " + exception.getMessage());
    }
}
```

#### iOS

```swift
import HUMAN

func setAdditionalDataForAccountDefender() {
    do {
        let additionalData: [String: String] = [
            "my_key1": "hello",
            "my_key2": "world"
        ]
        try HumanSecurity.AD.setAdditionalData(parameters: additionalData, forAppId: "<APP_ID>")
    } catch {
        print("Error: \(error)")
    }
}
```

**`Objective-C`**

```c title="Objective-C"
@import HUMAN;

- (void)setAdditionalDataForAccountDefender {
    NSMutableDictionary<NSString *, NSString *> *additionalData = [[NSMutableDictionary alloc] init];
    additionalData[@"my_key1"] = @"hello";
    additionalData[@"my_key2"] = @"world";

    NSError *error = nil;
    [HumanSecurity.AD setAdditionalDataWithParameters:additionalData forAppId:@"<APP_ID>" error:&error];
    if (error != nil) {
        NSLog(@"Error: %@", error);
    }
}
```