Skip to content
Java library for working with VK API
Branch: master
Clone or download
Latest commit f4e7435 Aug 27, 2019
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples v1.0.3 fix callbacks May 15, 2019
scripts Add travis May 19, 2019
sdk Version 1.0.6 (#165) Aug 26, 2019
.gitignore v5.100 Jul 1, 2019
.travis.yml Update travis config Aug 27, 2019
LICENSE Initial commit Aug 26, 2016 Add travis widget May 19, 2019
build.gradle Version 1.0.6 (#165) Aug 26, 2019
build.gradle.template Build.gradle template Aug 26, 2019
settings.gradle Add constants Dec 18, 2017

Java SDK for VK API

Build Status

Java library for VK API interaction, includes OAuth 2.0 authorization and API methods. Full VK API features documentation can be found here.

This library has been created using the VK API JSON Schema. It can be found here. It uses VK API version 5.73.

1. Prerequisites

2. Dependencies

VK Java SDK uses:

3. Latest release

Latest version: Maven

To add a dependency on VK Java SDK using Maven, use the following:


To add a dependency using Gradle:

dependencies {
  compile 'com.vk.api:sdk:LATEST_VERSION'

4. Prepare for using

Create a new VK application here to use VK Java SDK. Please choose an application type depending on which authorization pattern you need. It should be "Standalone" for Direct Authorization, "Web site" for Authorization Code Flow for server side requests and any of them for Client Credentials Flow.

Fill in the title, confirm the action via SMS and you will be redirected to the application settings page.

You will need your application ID (referenced as API_ID in the documentation), secure key (CLIENT_SECRET) and authorized redirect URI (REDIRECT_URI).

5. Logging

VK Java SDK uses SLF4J for logging. If you want to turn on logging, you must include a plugin that bridges SLF4J with a concrete logging framework. See SLF4J documentation.

JDK Logger




dependencies {
    compile group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.7.26'

Add file with configuration (located at your src/main/resources path):


Set java.util.logging.config.file system property:



    <!-- Binding for Log4J -->
    <!-- Log4j API and Core implementation required for binding -->


dependencies {
    //Binding for Log4J -->
    compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.11.2'
    //Log4j API and Core implementation required for binding
    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'

Add log4j2.xml file with configuration (located at your src/main/resources path):

<?xml version="1.0" encoding="UTF-8" ?>
<Configuration status="info">
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>

        <Root level="info">
            <AppenderRef ref="Console"/>

6. Initialization

Create VkApiClient object using the following code:

TransportClient transportClient = new HttpTransportClient();
VkApiClient vk = new VkApiClient(transportClient);

Note that you can use your own transport client. We use Apache Http Client.

7. Authorization

The library provides several authorization flows based on OAuth 2.0 protocol implementation in API. Please read the full documentation before you start.

7.1. Authorization Code Flow for User

OAuth 2.0 Authorization Code Flow allows calling methods from the server side.

This flow includes two steps — obtaining an authorization code and exchanging the code for an access token. Primarily you should obtain the "code" (manual) and then use this method to complete the flow:

UserAuthResponse authResponse = vk.oAuth()
    .userAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code)

UserActor actor = new UserActor(authResponse.getUserId(), authResponse.getAccessToken());

This takes your application ID, secure key, redirect URI, enumerated scopes and code obtained on the previous step of the flow.

When succeed, a UserActor object is created. You can call VK API methods on behalf of a user.

See example.

7.2. Authorization Code Flow for Community

The difference from the previous flow is that you send the groupId parameter to obtain the community's access token. Please read the full manual.

GroupAuthGroupResponse authResponse = vk.oAuth()
    .groupAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code)

GroupActor actor = new GroupActor(groupId, authResponse.getAccessTokens().get(groupId));

When succeed, a GroupActor object is created. You can call VK API methods on behalf of a community.

See example.

7.3. Handling need_validation error

Proceeding each of previous authorization flows you can receive a "need_validation" error. Use the following code to handle the error:

UserAuthResponse authResponse;
try {
    authResponse = vk.oAuth()
        .userAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code)
} catch (OAuthException e) {

UserActor actor = new UserActor(authResponse.getUserId(), authResponse.getAccessToken());

7.4. Client Credentials Flow

This flow allows to interact with API service methods with "secure" prefix. Use this method:

ServiceClientCredentialsFlowResponse authResponse = vk.oAuth()
    .serviceClientCredentialsFlow(APP_ID, CLIENT_SECRET)
ServiceActor actor = new ServiceActor(APP_ID, authResponse.getAccessToken());

When succeed, a ServiceActor object is created. You can call VK API methods on behalf of an app.

8. API Requests

You can find the full list of VK API methods here.

Request sample

GetResponse getResponse = vk.wall().get(actor)

Request sample with common method parameters:

List<UserXtrCounters> users = vk.users().get(actor)
    .fields(UserField.VERIFIED, UserField.SEX)

The full list of common parameters is available on this page.

Request sample for uploading and posting photos on user wall.

PhotoUpload serverResponse =;
WallUploadResponse uploadResponse = vk.upload().photoWall(serverResponse.getUploadUrl(), file).execute();
List<Photo> photoList =, uploadResponse.getPhoto())

Photo photo = photoList.get(0); 
String attachId = "photo" + photo.getOwnerId() + "_" + photo.getId();
GetResponse getResponse = vk.wall().post(actor)

9. Execute requests

You can find more information about execute method here.


JsonElement response = vk.execute().code(actor, "return API.wall.get({\"count\": 1})")

Storage function

JsonElement response = vk.execute().storageFunction(actor, "foo")
    .funcV(2) // set storage function version
    .unsafeParam("user_id", 1) // set storage function argument

Batch requests

JsonElement response = vk.execute().batch(actor,

10. Error Handling

Common Example

try {
        .message("Hello world")
} catch (ApiWallLinksForbiddenException e) {
    // Links posting is prohibited
} catch (ApiException e) {
    // Business logic error
} catch (ClientException e) {
    // Transport layer error

Captcha error handling

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) {
        .message("Hello world")

11. Callback API handler

Override methods from CallbackApi class for handling events

public class CallbackApiHandler extends CallbackApi {
  public void messageNew(Integer groupId, Message message) {

12. Callback API Long Poll handler

Enable Callback API Long Poll for needed group and specify which events should be tracked

HttpTransportClient httpClient = HttpTransportClient.getInstance();
VkApiClient vk = new VkApiClient(httpClient);

Override methods from CallbackApiLongPoll class for handling events and create needed constructors

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);

    public void messageNew(Integer groupId, Message message) {
      System.out.println("messageNew: " + message.toString());

    public void wallPostNew(Integer groupId, WallPost wallPost) {
      System.out.println("wallPostNew: " + wallPost.toString());

In order to use the created CallbackApiLongPollHandler which overrides methods from CallBackApiLongPoll, the instance of it needs to be created and method run called

CallbackApiLongPollHandler handler = new CallbackApiLongPollHandler(vk, groupActor);;

An example of usage Callback API Long Poll can be found in examples as a group-bot which logs all events.

13. Streaming API


//Init clients
TransportClient transportClient = new HttpTransportClient();

VkApiClient vkClient = new VkApiClient(transportClient);
VkStreamingApiClient streamingClient = new VkStreamingApiClient(transportClient);

//Create service actor
Integer appId = 4123123;
String accessToken = "sadf0asdf0asdfsadfassadf0asdf0asdfsadfassadf0asdf0asdfsadfas";
ServiceActor actor = new ServiceActor(appId, accessToken);

//Get streaming actor
GetServerUrlResponse getServerUrlResponse = vkClient.streaming().getServerUrl(actor).execute();
StreamingActor actor = new StreamingActor(getServerUrlResponse.getEndpoint(), getServerUrlResponse.getKey());

Add rule

//Create rule
String tag = "1";
String value = "ok";

StreamingResponse response = streamingClient.rules().add(actor, tag, value).execute();

Get rules

//Get rules
StreamingGetRulesResponse response = streamingClient.rules().get(actor).execute();

Delete rule

//Delete rule
String tag = "1";
streamingClient.rules().delete(actor, tag).execute();

Stream handler

Implement handle method from StreamingEventHandler class for handling stream events, new StreamingEventHandler() {
    public void handle(StreamingCallbackMessage message) {

14. Usage Example

As an SDK usage example we have released the YouTrack bot. The documentation can be found here.

You can’t perform that action at this time.