콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

navigation

SafetyNet Safe Browsing API

SafetyNet provides services for determining whether a URL has been marked as a known threat by Google.

Your app can use this API to determine whether a particular URL has been classified by Google as a known threat. Internally, SafetyNet implements a client for the Safe Browsing Network Protocol v4 developed by Google. Both the client code and the v4 network protocol were designed to preserve users' privacy and keep battery and bandwidth consumption to a minimum. Use this API to take full advantage of Google's Safe Browsing service on Android in the most resource-optimized way, and without implementing its network protocol.

This document explains how to use SafetyNet to check a URL for known threats.

Terms of Service

By using the Safe Browsing API, you consent to be bound by the Terms of Service. Please read and understand all applicable terms and policies before accessing the Safe Browsing API.

Requesting and registering an Android API key

To create an API key, follow these steps:

  1. Go to the Google Developers Console.
  2. On the upper toolbar, choose Select a project > your-project-name.
  3. In the search box, enter Safe Browsing APIs; when the Safe Browsing API name appears in the table, select it.
  4. After the page redisplays, select Enable and then select Go to Credentials.
  5. When the Add credentials to your project window appears, choose your parameters and then select What credentials do I need?.
  6. Enter a name for your API key and then select Create API key.
  7. Your new API key appears; copy and save this key for future use.

    Note: Your API key allows you to perform a URL check 10,000 times each day. The key, in this instance, should just be a hexadecimal string, not part of a URL.

  8. Select Done to complete the process.

If you need more help, check out the Google Developers Console Help Center.

Initializing the API

To use the Safe Browsing API, you must initialize the API by calling initSafeBrowsing() and waiting for it to complete. The following code snippet provides an example:

Tasks.await(SafetyNet.getClient(this).initSafeBrowsing());

Note: To minimize the impact of your app's initialization, call initSafeBrowsing() as early as possible in your activity's onResume() method.

Requesting a URL check

Your app can use a URL check to determine whether a URL poses a known threat. Some threat types may not be of interest to your particular app. The API allows you to choose which threat types are important for your needs. You can specify multiple known threat types.

Specifying threat types of interest

The constants in the SafeBrowsingThreat class contain the currently-supported threat types:

package com.google.android.gms.safetynet;

public class SafeBrowsingThreat {

  /**
   * This threat type identifies URLs of pages that are flagged as containing potentially
   * harmful applications.
   */
  public static final int TYPE_POTENTIALLY_HARMFUL_APPLICATION = 4;

  /**
   * This threat type identifies URLs of pages that are flagged as containing social
   * engineering threats.
   */
  public static final int TYPE_SOCIAL_ENGINEERING = 5;
}

When using the API, you must use constants that aren't marked as deprecated. You add threat type constants as arguments to the API. You may add as many threat type constants as your app requires.

Send the URL check request

The API is agnostic to the scheme used, so you can pass the URL with or without a scheme. For example, both

String url = "https://www.google.com";

and

String url = "www.google.com";

are valid.

SafetyNet.getClient(this).lookupUri(url,
          SAFE_BROWSING_API_KEY,
          SafeBrowsingThreat.TYPE_POTENTIALLY_HARMFUL_APPLICATION,
          SafeBrowsingThreat.TYPE_SOCIAL_ENGINEERING)
    .addOnSuccessListener(this,
        new OnSuccessListener() {
            @Override
            public void onSuccess(SafetyNetApi.SafeBrowsingResponse sbResponse) {
            // Indicates communication with the service was successful.
            // Identify any detected threats.
            if (sbResponse.getDetectedThreats().isEmpty()) {
                // No threats found.
            } else {
                // Threats found!
            }
         }
    })
    .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // An error occurred while communicating with the service.
                if (e instanceof ApiException) {
                    // An error with the Google Play Services API contains some
                    // additional details.
                    ApiException apiException = (ApiException) e;
                    Log.d(TAG, "Error: " + CommonStatusCodes
                        .getStatusCodeString(apiException.getStatusCode()));

                    // Note: If the status code, apiException.getStatusCode(),
                    // is SafetyNetstatusCode.SAFE_BROWSING_API_NOT_INITIALIZED,
                    // you need to call initSafeBrowsing(). It means either you
                    // haven't called initSafeBrowsing() before or that it needs
                    // to be called again due to an internal error.
                } else {
                    // A different, unknown type of error occurred.
                    Log.d(TAG, "Error: " + e.getMessage());
                }
            }
    });

Read the URL check response

Using the returned SafetyNetApi.SafeBrowsingResponse object, call its getDetectedThreats() method, which returns a list of SafeBrowsingThreat objects. If the returned list is empty, the API didn't detect any known threats. If the list isn't empty, however, call getThreatType() on each element in the list to determine which known threats the API detected.

Shutting down your Safe Browsing session

If your app won't be using the Safe Browsing API for a prolonged period of time, check all the necessary URLs within your app and then shut down your Safe Browsing session using the shutdownSafeBrowsing() method:

SafetyNet.getClient(this).shutdownSafeBrowsing();

We recommend that you call shutdownSafeBrowsing() in your activity's onPause() method, and that you call initSafeBrowsing() in your activity's onResume() method. However, you should make sure that initSafeBrowsing() has finished executing before calling lookupUri(). By making sure that your session is always fresh, you'll help reduce internal errors in your app.

Suggested warning language

To see suggested warning language, see the Safe Browsing API Developer's Guide.

이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)