Developers » Java SDK
1. Prerequisites
2. Dependencies
VK Java SDK uses:
3. Latest release
The most recent release is 0.5.12, released Feb 27, 2018.

To add a dependency on VK Java SDK using Maven, use the following:
<dependency>
  <groupId>com.vk.api</groupId>
  <artifactId>sdk</artifactId>
  <version>0.5.12</version>
</dependency>

To add a dependency using Gradle:
dependencies {
  compile 'com.vk.api:sdk:0.5.12'
}
4. Prepare for using
Create a new VK app here to use VK Java SDK. Please choose an app 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 app's settings page.

You will need your app ID (referenced as API_ID), 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
Maven:
<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-jdk14</artifactId>
        <version>1.7.22</version>
    </dependency>
</dependencies>


Gradle:
dependencies {
    compile group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.7.22'
}


Add logging.properties file with configuration (located at your src/main/resources path):
.level=INFO
handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINEST
deng.level=FINEST


Set java.util.logging.config.file system property:
-Djava.util.logging.config.file=logging.properties

log4j2
Maven:
<dependencies>
     Binding for Log4J -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>2.7</version>
    </dependency>

<!-- Log4j API and Core implementation required for binding -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.7</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.7</version>
    </dependency>
</dependencies>


Gradle:
dependencies {
    //Binding for Log4J
    compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.7'

//Log4j API and Core implementation required for binding
    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.7'
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.7'
}


Add log4j2.xml file with configuration (located at your src/main/resources path):
<?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>
6. Initialization
Create VkApiClient object using the following code:
TransportClient transportClient = HttpTransportClient.getInstance();
VkApiClient vk = new VkApiClient(transportClient, new Gson());

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 vk.com 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. Primarly 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)
    .execute();

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

This takes your app 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.
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.
GroupAuthResponse authResponse = vk.oauth()
    .groupAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code)
    .execute();

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.
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:
try {
    UserAuthResponse 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());


7.4. Client Credentials Flow
This flow allows to interact with service access token. Use this method:
ServiceClientCredentialsFlowResponse authResponse = vk.oauth()
    .serviceClientCredentionalsFlow(APP_ID, CLIENT_SECRET)
    .execute();

ServiceActor actor = new ServiceActor(APP_ID, authResponse.getAccessToken());

When succeed, a ServerActor 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.
8.1. Request sample
GetResponse getResponse = vk.wall().get(actor)
    .ownerId(1)
    .count(100)
    .offset(5)
    .filter("owner")
    .execute();

8.2. Request sample with common method parameters
List<UserXtrCounters> users = vk.users().get(actor)
    .userIds("1")
    .fields(UserField.VERIFIED, UserField.SEX)
    .lang(Lang.EN)
    .execute();


The full list of common parameters is here: this page.
8.4. Request sample for uploading and posting photos
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();
9. Execute requests
You can find more information about execute method here.
Code
JsonElement response = vk.execute().code(actor, "return API.wall.get({"count": 1})")
    .execute();

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

Batch requests
JsonElement response = vk.execute().batch(actor,
        vk.database().getChairs(1).count(10),
        vk.database().getCities(1),
        vk.groups().getMembers(actor).groupId(groupId)
).execute();
9. Error Handling
Common Example
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 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) {
    vk.wall().post(actor)
        .message("Hello world")
        .captchaSid(captchaSid)
        .captchaKey(captchaKey)
        .execute();
}
11. Callback API handler
Override methods from CallbackApi class for handling events
public class CallbackApiHandler extends CallbackApi {
  @Override
  public void messageNew(Integer groupId, Message message) {
    System.out.println(message.getBody());
  }
}

...
CallbackApiHandler callbackApiHandler = new CallbackApiHandler();

String body = httpRequest.getBody();
callbackApiHandler.parse(body);
12. Using Streaming API
12.1. Initialization
//Init clients
TransportClient transportClient = new HttpTransportClient();

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

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

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

12.2. Adding rule
String tag = "1";
String value = "ok";

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

12.3. Getting rules
StreamingGetRulesResponse response = streamingClient.rules().get(actor).execute();

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

12.5. Getting stream
streamingClient.stream().get(actor, new StreamingEventHandler() {
    @Override
    public void handle(StreamingCallbackMessage message) {
        System.out.println(message);
    }
}).execute();
13. Usage Example
YouTrack bot: https://github.com/VKCOM/vk-java-sdk/wiki/Y