- Android для начинающих: использование REST API
- 1. Включение доступа к Интернету
- 2. Создание фоновых потоков
- 3. Создание HTTP-соединения
- 4. Добавление заголовков запросов
- 5. Чтение ответов
- 6. Разбор JSON ответов
- 7. Использование разных HTTP методов
- 8. Кэширование ответов
- Заключение
- Get Started
- Step 1: Get Google Play services
- Step 2: Get a Google account
- Step 3: Get an API key
- Obtain the SHA1 fingerprint of your certificate
- Step 4: Configure your project
- Step 5: Publish and subscribe
- Securing API Keys in Android App using NDK (Native Development Kit)
- Requirements
- The Android Native Development Kit (NDK):
- CMake:
- Two ways for using NDK: ndk-build, CMake
- — — CMake:
- — — ndk-build:
- CMake or ndk-build .
- ***Securing Keys using ndk-build…(Item-01)
- ***Securing Keys using CMake…(item-02)
- ***** The easiest and best way*****
Android для начинающих: использование REST API
Russian (Pусский) translation by Ilya Nikov (you can also view the original English article)
Большинство из нас стали весьма жадны до новой информации, что в Интернете является такой важной частью нашей жизни. Поэтому создание приложений Android со статичным контентом может быть плохой идеей. Вместо этого вам следует рассмотреть возможность создания приложений, которые могут отображать свежий контент каждый раз, когда пользователь их открывает.
Это может звучать сложно, но с большим количеством сайтов, которые раскрывают свои ресурсы через REST API, на самом деле это довольно просто. (Смотрите руководство для начинающих по HTTP и REST для примера.)
В этом уроке я расскажу вам, как использовать классы и методы, доступные в Android SDK, для подключения к удаленным веб-серверам и взаимодействия с ними с использованием их REST API.
1. Включение доступа к Интернету
Использование REST API, очевидно, связано с использованием Интернета. Тем не менее, приложения Android могут получить доступ к Интернету только в том случае, если у них есть разрешение android.permission.INTERNET . Поэтому перед началом написания любого сетевого кода вы должны убедиться, что в файле манифеста вашего проекта присутствуют следующие uses-permission теги:
Поскольку android.permission.INTERNET не считается опасным разрешением, вам не нужно запрашивать его во время выполнения на устройствах с уровнем API 23 или выше.
2. Создание фоновых потоков
Платформа Android не позволяет выполнять сетевые операции в основном потоке приложения. Поэтому весь ваш сетевой код должен принадлежать фоновому потоку. Самый простой способ создать такой поток — использовать метод execute() класса AsyncTask . В качестве единственного аргумента execute() ожидает объект Runnable .
Если вы хотите узнать больше о выполнении операций в фоновом потоке, я предлагаю вам прочитать этот учебник о фоновых операциях из серии Android для начинающих.
3. Создание HTTP-соединения
Используя метод openConnection() класса URL , вы можете быстро настроить соединение с любой конечной точкой REST. Возвращаемое значение openConnection() должно быть передано в экземпляр HttpURLConnection или HttpsURLConnection , в зависимости от доступа к конечной точке через HTTP или HTTPS. Оба HttpURLConnection и HttpsURLConnection позволяют выполнять такие операции, как добавление заголовков запросов и чтение ответов.
В следующем фрагменте кода показано, как настроить соединение с корневой конечной точкой API GitHub:
Обратите внимание, что HttpsURLConnection является подклассом класса HttpURLConnection .
4. Добавление заголовков запросов
Большинство веб-сайтов, предлагающих REST API, хотят иметь возможность однозначно идентифицировать ваше приложение. Самый простой способ помочь им сделать это — включить уникальный заголовок User-Agent во все ваши запросы.
Чтобы добавить заголовок User-Agent в ваш запрос, вы должны использовать метод setRequestProperty() объекта HttpURLConnection . Например, вот как вы устанавливаете заголовок User-Agent в my-rest-app-v0.1:
Вы можете добавить несколько заголовков к своему запросу, вызвав несколько раз метод setRequestProperty() . Например, следующий фрагмент кода добавляет заголовок Accept и кастомный заголовок Contact-Me :
5. Чтение ответов
После того как вы передали все заголовки запросов, вы можете проверить, есть ли у вас валидный ответ, используя метод getResponseCode() объекта HttpURLConnection .
Если класс HttpURLConnection получает код ответа на перенаправление, например 301, он автоматически обрабатывает его и следует за перенаправлением. Поэтому, как правило, вам не нужно будет писать дополнительный код для проверки перенаправления.
В случае отсутствия ошибок вы можете теперь вызвать метод getInputStream() , чтобы получить ссылку на входящий поток соединения.
Большинство REST API в наши дни возвращают данные, отформатированные как документы JSON. Поэтому, вместо прямого чтения из объекта InputStream , я предлагаю вам создать для него InputStreamReader .
6. Разбор JSON ответов
Android SDK имеет класс JsonReader, который позволяет легко разбирать документы JSON. Вы можете создать новый экземпляр класса JsonReader , передав объект InputStreamReader его конструктору.
То как вы извлекаете определенную часть информации из документа JSON, зависит от его структуры. Например, документ JSON, возвращаемый корневой конечной точкой REST API GitHub, выглядит следующим образом:
Как вы можете видеть, ответ — это только один большой объект JSON, содержащий несколько ключей. Чтобы извлечь из него значение с именем organization_url, вам нужно будет написать следующий код:
Вышеупомянутый код обрабатывает ответ JSON как поток токенов. Поэтому он потребляет очень мало памяти. Однако, поскольку он должен обрабатывать каждый отдельный токен один за другим, он может оказаться медленным при обработке больших ответов.
После того как вы извлечете всю необходимую информацию, вы всегда должны вызвать метод close() для объекта JsonReader , чтобы он освобождал все сохраненные ресурсы.
Вы также должны закрыть соединение, вызвав метод disconnect() объекта HttpURLConnection .
7. Использование разных HTTP методов
HTTP-интерфейсы REST используют методы HTTP для определения типа операции, которая должна выполняться над ресурсом. На предыдущих шагах мы использовали метод HTTP GET для выполнения операции чтения. Поскольку класс HttpURLConnection использует по умолчанию метод GET , нам не нужно было его явно указывать.
Чтобы изменить метод HTTP вашего объекта HttpURLConnection , вы должны использовать его метод setRequestMethod() . Например, следующий фрагмент кода открывает соединение с конечной точкой, принадлежащей httpbin.org, и устанавливает свой HTTP-метод в POST :
Как вы уже знаете, POST -запросы используются для отправки данных на сервер. При записи в выходной поток соединения вы можете легко добавить любые данные в тело запроса POST . Однако, прежде чем вы это сделаете, вы должны убедиться, что вы вызываете метод setDoOutput() объекта HttpURLConnection и передаете ему значение true .
В следующем фрагменте кода показано, как отправить на сервер простую пару «ключ-значение»:
8. Кэширование ответов
Всегда рекомендуется кэшировать ответы HTTP. Таким образом, вы можете не только сократить потребление пропускной способности вашего приложения, но и сделать его более отзывчивым. Начиная с уровня API 13, Android SDK предлагает класс HttpResponseCache , который позволяет легко реализовать кэширование без каких-либо изменений в вашей сетевой логике.
Чтобы установить кэш для вашего приложения, вы должны вызвать метод install() класса HttpResponseCache . Метод ожидает абсолютный путь, указывающий, где должен быть установлен кеш, и число, определяющее размер кеша. Вы можете использовать метод getCacheDir() , если вы не хотите указывать абсолютный путь вручную.
В следующем фрагменте кода устанавливается кеш размером 100 000 байт:
Как только кеш установлен, класс HttpURLConnection начинает использовать его автоматически. Чтобы проверить, работает ли ваш кеш, вы можете использовать его метод getHitCount() , который возвращает количество HTTP-ответов, которые были отправлены из кеша.
Заключение
Существуют тысячи REST API-интерфейсов, которые вы можете свободно использовать в своих приложениях для Android. Используя их, вы можете сделать ваше приложение более информативным, интересным и многофункциональным. В этом уроке вы узнали, как использовать класс HttpURLConnection для использования таких REST API. Вы также узнали, как создать кеш ответов HTTP, который снижает использование потребление сетевого трафика вашим приложением.
Если вы считаете, что использование HttpURLConnection слишком сложное, вам следует обратить внимание на сторонние библиотеки, такие как например, Volley. Библиотеки, подобные этой, используют класс HttpURLConnection внутри, но предоставляют множество удобных методов, которые позволяют сделать ваш код более кратким и читаемым.
Чтобы узнать больше о работе с сетью на платформе Android, вы можете обратиться к руководству по сетевым операциям Android.
Источник
Get Started
This document explains how to start developing with the Nearby Messages API on Android. The Nearby Messages API is part of Google Play services.
Step 1: Get Google Play services
The Nearby Messages API is available on Android devices with Google Play services 7.8.0 or higher. Devices running Android 2.3 or higher that have the Google Play Store app automatically receive updates to Google Play services. To check which version of Google Play services is installed on your device, go to Settings > Apps > Google Play services.
Ensure that you have the latest client library for Google Play services on your development host:
Under Appearance & Behavior > System Settings > Android SDK > SDK Tools, ensure that the following packages are installed:
- Google Play services
- Google Repository
Step 2: Get a Google account
To use the Nearby Messages APIs, you need a Google Account. This is so that you, the developer, can enable the Nearby API in the next step (your users will not need to have a Google account). If you already have an account, then you’re all set. You may also want a separate Google Account for testing purposes.
Step 3: Get an API key
Take these steps to enable the Google Nearby Messages API for Android and get an API key:
- Go to the Google Developers Console.
- Create or select a project to register your application with.
- Click Continue to Enable the API.
- On the Credentials page, create a new Android key (and set the API Credentials).
Note: If you have an existing Android key, you may use that key. - In the resulting dialog, enter your app’s SHA-1 fingerprint and package name. For example:
- Your new Android API key appears in the list of API keys for your project. An API key is a string of characters, something like this:
Obtain the SHA1 fingerprint of your certificate
To create a new API key for your Android app, you need the SHA1 fingerprint of the certificate you use to sign your APK. Messages can only be exchanged between apps that are signed with API keys from the same project.
To obtain this fingerprint:
- Find the location of your keystore.
- In a terminal, run the keytool utility from the JDK. For example, if you are using the `debug` keystore:
Note: For the debug keystore, the password is android . On Mac OS and Linux, the debug keystore is typically located at
/.android/ debug.keystore . On Windows, it is typically located at %USERPROFILE%\ .android\ debug.keystore .
Step 4: Configure your project
Android Studio makes it easy to create a project for the Nearby Messages API. Follow the steps described in Creating a Project to create a new project. In Android Studio, open the build.gradle file for your module and add the Google Play services client library as a dependency:
Then, configure your manifest with the API Key generated in the previous step:
Step 5: Publish and subscribe
In your app, start using the Nearby Messages API.
The Nearby Messages API requires user consent. When either publish or subscribe is first invoked, Nearby will show an opt in dialog.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Securing API Keys in Android App using NDK (Native Development Kit)
Securing API keys in Android application has become a challenging by traditional methods (storing them in strings.xml or in Gradle etc.), since they can be easily exposed by reverse engineering the app. It may lead to privacy issues and also may affect the billing for third party paid API access.
Though its not possible to fully protect this API keys from reverse engineering but we can make extra laye r for security by using NDK in our app.
The NDK (Native Development Kit) allows to write code in C/C++ in our app. And the good news is that ndk libraries can not be decompiled easily which make the APIs harder to find.
Today, We are going to store API keys in the native C/C++ class and accessing them in our Java classes. Now Let’s started:
Requirements
To compile and debug native code for our app, we need the following components:
The Android Native Development Kit (NDK):
a set of tools that allows to use C and C++ code with Android.
CMake:
an external build tool that works alongside Gradle to build your native library. You do not need this component if you only plan to use ndk-build.
the debugger Android Studio uses to debug native code.
You can install these components using the SDK Manager:
- From an open project, select Tools > Android > SDK Manager from the menu bar.
- Click the SDK Tools tab.
- Check the boxes next to LLDB, CMake, and NDK, as shown in below figure:
Two ways for using NDK: ndk-build, CMake
- NDK is a collection of compilers and libraries that are needed to build C/C++ code for android.
- ndk-build and CMake both use the NDK and solve the same problem.
— — CMake:
- CMake is a new way and the default build tool for using ndk. If we are creating new native library , then we should use CMake.
— — ndk-build:
- Android studio also support this ndk-build(this is a build system included in NDK) due to the large number of existing projects that use the build toolkit to compile their native code.
- It uses android.mk files. in other way we can say android.mk file contains ndk-build.
- If you use CMake then you don’t need Android.mk instead you will need CMakeList.txt
CMake or ndk-build .
- If you’re not familiar with either or your project is cross platform, CMake is probably the better choice. Because CMake’s main advantage is that you can use one set of build files for all your targets (Android, Linux, Windows, iOS, etc).
- ndk-build should be preferred if you’re building a project that already uses Android.mk files for its build system (legacy projects).
***Securing Keys using ndk-build…(Item-01)
step 01: Create a folder “jni” under src/main.
step 02: Create a file ‘Android.mk’ under “jni” folder with following content:
step 03: Create another file ‘Application.mk’ file under “jni” folder with the following content:
Here, This is for setting different Application Binary Interface or ABI. More details can be found at Application.mk.
step 04: Create the C/C++ file “keys.c” under “jni” folder. Add the following content to it:
- “Java_com_shishirstudio_ndktest_MainActivity_getFacebookApiKey”: represents the Java code with package name “com.shishirstudio.ndktest” [ dot(.) must be replaced with underscore(_)]followed by Activity name “MainActivity” where we want to call the native function and the static method “getFacebookApiKey” to fetch the API key from the native function. So the combination is:< Package Name>_
_ - In the above code, I have encoded the actual API key using Base64 encoding (You can store actual API key) for making another security layer.
step 05: Add a static block and load the library ‘keys’ in the activity where you will access the keys. (In our case in MainActivity).
step 06: We also have to add member functions of type “native” to access the keys from the C/C++ file. Since we stored 2 keys, we will declare 2 functions:
step 07: Now access the keys in the code like:
step 08: Oh ! one more things, to compile or make the native build using NDK, don’t forget to add entry into the gradle file:
step 09: Now, sync and build the project. And you will find everything is ok….
***Securing Keys using CMake…(item-02)
step 01: Create a new project or use existing project.
step 02: Create a folder named “cpp” under src/main.
step 03: Create the C/C++ file “native-lib.cpp” under “cpp” folder. And add the following content to it:
- “Java_com_shishirstudio_ndktest_MainActivity_stringFromJNI”: represents the Java code with package name “com.shishirstudio.ndktest” [ dot(.) must be replaced with underscore(_)]followed by Activity name “MainActivity” where we want to call the native function and the static method “stringFromJNI” to fetch the API key from the native function. So the combination is:< Package Name>_
_
Now the directory looks like below…
step 04: Create a CMake build script CMakeLists.txt under app folder ( This is a plain text file that you must name CMakeLists.txt ) and add the following content to it.
Step 05: Now, our C/C++ native files and Java code are ready. But to compile or make the native build using NDK, we need to add entry into the gradle file:
Step 06: To use this API follow the step 05,06 and 07 of item-01.
***** The easiest and best way*****
In the newer updates of Android Studio its very easy because everything will be ready for you automatically. Just follow the below step:-
step 01: Enable “include C++ support” while taking a new project in android studio.
Источник