The translation was generated automatically and may contain mistakes
Java SDK
The Java SDK page on Github:
https://github.com/VKCOM/vk-java-sdk .
A Java library for interacting with the VKontakte API, making it easier to implement OAuth authorization and call API methods.
This library was created using the JSON Schema VK API.
JSON Schema project page on Github:
https://github.com/VKCOM/vk-api-schema .
The scheme is used aPI version — 5.131.
Requirements
Dependencies
The project uses:
- •Apache Http Client Version 4.5.8.
- •SLF4J Version 1.7.26.
- •Apache Commons Lang Version 3.6.
- •Apache Commons Collections Version 4.3.
- •Apache Commons IO Version 2.6.
- •Google Gson and version 2.8.5.
Current version
Actual release date .
Connecting Dependency to Maven: '''maven com.vk.api sdk LATEST_VERSION
Подключение зависимости в Gradle:
```gradle
dependencies {
compile 'com.vk.api:sdk:LATEST_VERSION'
}
Connecting Dependency to SBT:
libraryDependencies += "com.vk.api" % "sdk" % "LATEST_VERSION"Preparation for use
Create an app VKontakte . Choose the right type.
Indicate the name, confirm the action by SMS. You will be redirected to the Settings page.
In the future, you will need the application ID (in the documentation it is denoted as API_ID The secret key ( CLIENT_SECRET ) and a trusted redirect URI ( REDIRECT_URI ).
Logging
The library uses SLF4J for logging. To enable logging, you need to add a binding for a specific logging framework. More details in sLF4J documentation .
JDK Logger
Maven:
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.26</version>
</dependency>
</dependencies>Gradle:
dependencies {
compile group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.7.26'
}Add a file logging.properties configuration (located in src/main/resources )
.level=INFO
handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINEST
deng.level=FINESTInstall a system variable that points the way to the file: '''java -Djava.util.logging.config.file=logging.properties
### log4j2
Maven:
```maven
<dependencies>
<!-- Binding for Log4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.2</version>
</dependency>
<!-- Log4j API and Core implementation required for binding -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>
</dependencies>
Gradle: '''gradle dependencies { //Binding for Log4J --> compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.11.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.11.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.11.2'```
}Добавить конфигурационный фай?1?» src/main/resources/log4j2.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration status="info">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>Initialization
Create an object VkApiClient as follows:
'''java
TransportClient transportClient = new HttpTransportClient();
VkApiClient vk = new VkApiClient(transportClient);
Обратите внимание, вы можете использовать транспортный клиент по своему выбору. Мы используем [Apache Http Client](https://hc.apache.org/).
## Авторизация
Библиотека предусматривает несколько способов авторизации, основанны?1?… на реализации `OAuth 2.0` в API ?1?’Контакте. Пожалуйста, ознакомьтесь с [документацией](api/access-token/getting-started), прежде чем начать.
### Authorization Code Flow для пользователя
<!-- не актуальное -->
Authorization Code Flow позволяет вызывать методы API с серверной стороны.
Эта схема авторизации состоит из дву?1?… этапов — получение авторизационного кода (`code`) и обмен его на ключ доступа. Сначала вам необходимо получить `code` ([инструкция](api/access-token/authcode-flow-user)), а затем выполнить второй этап:
```java
UserAuthResponse authResponse = vk.oAuth()
.userAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code)
.execute();
UserActor actor = new UserActor(authResponse.getUserId(), authResponse.getAccessToken());
The method takes as parameters ID applications, the secret key, redirect URI , the list rights of access and code received in the first stage.
After successful implementation, an object will be created.. UserActor . You can access the API VKontakte on behalf of the user.
Authorization Code Flow for the community
The difference between this scheme and the previous one is that you need to pass a parameter groupId to get the community access key. Please read it detailed guidance .
'''java
GroupAuthResponse authResponse = vk.oAuth()
.groupAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code)
.execute();
GroupActor actor = new GroupActor(groupId, authResponse.getAccessTokens().get(groupId));
После успешного выполнения будет создан объект `GroupActor`. ?1?’ы можете обращаться к API ?1?’Контакте от имени сообщества.
### Обработка ошибки `need_validation`
?1?’ процессе авторизации вы можете получить ошибку `"need_validation"`. Используйте такой код для ее обработки:
```java
UserAuthResponse authResponse;
try {
authResponse = vk.oAuth()
.userAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code)
.execute();
} catch (OAuthException e) {
e.getRedirectUri();
}
UserActor actor = new UserActor(authResponse.getUserId(), authResponse.getAccessToken());
Client Credentials Flow
This scheme allows you to get the access key to work with the methods of the section secure . Note that the key is IP-bound and not suitable for other methods. We recommend using the service key from the application settings.
'''java ServiceClientCredentialsFlowResponse authResponse = vk.oAuth() .serviceClientCredentialsFlow(APP_ID, CLIENT_SECRET) .execute();
ServiceActor actor = new ServiceActor(APP_ID, authResponse.getAccessToken());
После успешного выполнения будет создан объект `ServiceActor` и вы сможете вызывать методы VK API от имени приложения.
## Запросы к API
[Полный список методов API](method).
### Запрос от имени пользователя
```java
GetResponse getResponse = vk.wall().get(actor)
.ownerId(1)
.count(100)
.offset(5)
.filter("owner")
.execute();
Query with universal parameters
'''java List users = vk.users().get(actor) .userIds("1") .fields(UserField.VERIFIED, UserField.SEX) .lang(Lang.EN) .execute();
[Полный список параметров](api/api-requests).
### Публикация фотографии на стене пользователя
```java
PhotoUpload serverResponse = vk.photos().getWallUploadServer(actor).execute();
WallUploadResponse uploadResponse = vk.upload().photoWall(serverResponse.getUploadUrl(), file).execute();
List<Photo> photoList = vk.photos().saveWallPhoto(actor, uploadResponse.getPhoto())
.server(uploadResponse.getServer())
.hash(uploadResponse.getHash())
.execute();
Photo photo = photoList.get(0);
String attachId = "photo" + photo.getOwnerId() + "_" + photo.getId();
GetResponse getResponse = vk.wall().post(actor)
.attachments(attachId)
.execute();
Execute Requests
Details of the Execute Method .
Usage code
'''java JsonElement response = vk.execute().code(actor, "return API.wall.get({"count": 1})") .execute();
### Хранимая процедура
```java
JsonElement response = vk.execute().storageFunction(actor, "foo")
.funcV(2) // set storage function version
.unsafeParam("user_id", 1) // set storage function argument
.execute();
Package requests
'''java JsonElement response = vk.execute().batch(actor, vk.database().getChairs(1).count(10), vk.database().getCities(1), vk.groups().getMembers(actor).groupId(groupId) ).execute();
## Обработка ошибок
### Общий случай
```java
try {
vk.wall().post(actor)
.message("Hello world")
.execute();
} catch (ApiWallLinksForbiddenException e) {
// Links posting is prohibited
} catch (ApiException e) {
// Business logic error
} catch (ClientException e) {
// Transport layer error
}
Captcha
'''java String captchaSid = null; String captchaImg = null;
try { vk.wall().post(actor).message("Hello world").execute(); } catch (ApiCaptchaException e) { captchaSid = e.getCaptchaSid(); captchaImg = e.getCaptchaImg(); }
//Showing captcha image...
if (captchaImg != null) { vk.wall().post(actor) .message("Hello world") .captchaSid(captchaSid) .captchaKey(captchaKey) .execute(); }
## Обработка событий Callback API
Переопределите методы из класса CallbackApi, чтобы обрабатывать события:
```java
public class CallbackApiHandler extends CallbackApi {
@Override
public void messageNew(Integer groupId, Message message) {
System.out.println(message.getText());
}
}
Callback API Long Poll event handling
Enable the Long Poll Callback API for the desired community and select the events you want to follow. '''java HttpTransportClient httpClient = HttpTransportClient.getInstance(); VkApiClient vk = new VkApiClient(httpClient); vk.groups().setLongPollSettings(groupActor).enabled(true) .wallPostNew(true) .messageNew(true) .execute();
Переопределите методы из класса `CallbackApiLongPoll`, чтобы обрабатывать события, и создайте нужный конструктор:
```java
public class CallbackApiLongPollHandler extends CallbackApiLongPoll {
public CallbackApiLongPollHandler(VkApiClient client, UserActor actor, Integer groupId) {
super(client, actor, groupId);
}
public CallbackApiLongPollHandler(VkApiClient client, GroupActor actor) {
super(client, actor);
}
@Override
public void messageNew(Integer groupId, Message message) {
System.out.println("messageNew: " + message.toString());
}
@Override
public void wallPostNew(Integer groupId, WallPost wallPost) {
System.out.println("wallPostNew: " + wallPost.toString());
}
}
To use the created CallbackApiLongPollHandler which redefines the methods of CallBackApiLongPoll , you need to instantiate it and call the method run
'''java CallbackApiLongPollHandler handler = new CallbackApiLongPollHandler(vk, groupActor); handler.run();
Пример использования Callback API Long Poll можно найти в разделе `examples` как `group-bot`, который логирует все события.
## Примеры использования
?1?’ качестве примера использования SDK мы выпустили бота [YouTrack](https://github.com/VKCOM/vk-java-sdk/wiki/YouTrack-bot).