• Stars
    star
    290
  • Rank 142,981 (Top 3 %)
  • Language
    Java
  • License
    MIT License
  • Created over 8 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Java library for working with VK API

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.131.

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:

<dependency>
  <groupId>com.vk.api</groupId>
  <artifactId>sdk</artifactId>
  <version>LATEST_VERSION</version>
</dependency>

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

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 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.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:

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">
    <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 = 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 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. 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)
    .execute();

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.

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:

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

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)
    .execute();
    
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)
    .ownerId(1)
    .count(100)
    .offset(5)
    .filter("owner")
    .execute();

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 available on this page.

Request sample for uploading and posting photos on user wall.

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

10. 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.getText());
  }
}

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);
vk.groups().setLongPollSettings(groupActor).enabled(true)
                                           .wallPostNew(true)
                                           .messageNew(true)
                                           .execute();

(WIP) 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);
    }

    @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());
    }
}

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);
handler.run();

13. Streaming API

Initialization

//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

streamingClient.stream().get(actor, new StreamingEventHandler() {
    @Override
    public void handle(StreamingCallbackMessage message) {
        System.out.println(message);
    }
}).execute();

14. Usage Example

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

More Repositories

1

kphp

KPHP — a PHP compiler
C++
1,322
star
2

VKUI

VKUI – это набор React-компонентов, с помощью которых можно создавать интерфейсы, внешне неотличимые от наших iOS и Android приложений.
TypeScript
995
star
3

YouTokenToMe

Unsupervised text tokenizer focused on computational efficiency
C++
951
star
4

noverify

Pretty fast linter (code static analysis utility) for PHP
Go
667
star
5

vk-android-sdk

Android library for working with VK API, authorization through VK app, using VK functions.
Kotlin
458
star
6

vk-ios-sdk

iOS library for working with VK API, authorization through VK app, using VK functions
Objective-C
298
star
7

vk-api-schema

JSON Schema of VK API
Shell
206
star
8

statshouse

StatsHouse is a highly available, scalable, multitenant monitoring system
C
206
star
9

vk-php-sdk

PHP library for working with VK API
PHP
204
star
10

vkompose

Kotlin Compiler Plugins, an IDEA Plugin, and a Detekt Rule that will help to improve your experience with Jetpack Compose
Kotlin
190
star
11

kittenhouse

Go
185
star
12

lighthouse

Lightweight interface for ClickHouse
JavaScript
185
star
13

joy4

Golang audio/video library and streaming server
Go
180
star
14

nocolor

Validate the architecture of your PHP project based on the concept of function colors
Go
161
star
15

nginx-quic

C
151
star
16

KNet

Android network library with QUIC protocol supporting.
Kotlin
148
star
17

nocc

A distributed C++ compiler: like distcc, but faster
Go
142
star
18

bot-example-php

Пример бота для VK
PHP
134
star
19

icons

Набор SVG иконок, представленный в виде React компонентов.
JavaScript
124
star
20

vk-bridge

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web
TypeScript
70
star
21

php-parser

PHP parser written in Go
Go
69
star
22

modulite

A plugin for PHPStorm that brings modules to the PHP language
Kotlin
65
star
23

vk-qr

VK QR Code generator library
TypeScript
58
star
24

create-vk-mini-app

Create VK Apps with no build configuration.
TypeScript
53
star
25

vk-miniapps-deploy

NPM module for deploy VK Mini Apps on VK hosting
JavaScript
49
star
26

kphpstorm

A PhpStorm plugin that makes IDE understand KPHP specifics
Kotlin
41
star
27

vkui-tokens

TypeScript
39
star
28

fastXDM

fast library for cross-domain messaging
JavaScript
39
star
29

node-vk-call

Simple API wrapper for VK.com social network
JavaScript
35
star
30

elephize

Typescript to PHP translation tool
TypeScript
33
star
31

vk-streaming-api

Go
33
star
32

vk-mini-apps-api

The official package for quick and easy development of VK Mini Apps
TypeScript
28
star
33

vk-mini-apps-router

TypeScript
27
star
34

Appearance

JavaScript
26
star
35

vkid-android-sdk

Kotlin
25
star
36

vkjs

VK shared JS libs
TypeScript
23
star
37

vk-router

TypeScript
22
star
38

vk-windowsphone-sdk

VK SDK for Windows Phone
C#
22
star
39

admstorm

PhpStorm plugin aimed at simplifying tasks at the junction of the local repository and the repository on the dev server
Kotlin
20
star
40

vk-unity-sdk

C#
20
star
41

vk-tunnel-client

TypeScript
19
star
42

kive

Go
19
star
43

tl

C++
18
star
44

vkdata-sketchplugin

Sketch plugin for using data from your account at vk.com
JavaScript
17
star
45

vk-apps-launch-params

Пример работы с параметрами запуска
JavaScript
17
star
46

nginx-http-vkupload-module

C
16
star
47

kphp-polyfills

PHP implementations of functions supported by KPHP natively (a Composer package)
PHP
15
star
48

superappkit-android-demo

Kotlin
15
star
49

vkid-web-sdk

TypeScript
15
star
50

vk-mini-apps-examples

TypeScript
15
star
51

IOSDevice

A set of hacks and workarounds for iOS Safari & Co.
JavaScript
14
star
52

docker-emulator-android

Dockerfile
13
star
53

modulite-phpstan

Bring modules into PHP and PHPStan
PHP
13
star
54

vk-apps-tensorflow-example

VK apps + tensorflow-js demo app
JavaScript
12
star
55

api-schema-typescript-generator

TypeScript
11
star
56

vkid-ios-sdk

Swift
11
star
57

api-schema-typescript

TypeScript
10
star
58

VKSDK-iOS

Swift
10
star
59

Delegate

Python
10
star
60

engine-go

Common libraries for our go engines (microservices)
Go
10
star
61

vk-direct-games-example

JavaScript
10
star
62

vk-ios-urlprotocol-example

This is an example iOS app with custom URLProtocol
Swift
10
star
63

swc-plugin-css-modules

Rust
9
star
64

vk-bridge-mock

The VK Bridge mock library
TypeScript
9
star
65

ktest

Test and benchmark KPHP code
Go
9
star
66

vk-ads-retargeting-demo

Демонстрация JavaScript API ретаргетинга ВКонтакте
HTML
8
star
67

eslint-config

JavaScript
8
star
68

useWeb3

JavaScript
8
star
69

TL-Schema-idea-plugin

Plugin for JetBrains products for coloring TL Schema files
Java
8
star
70

vk-connect-promise

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web with events based on promises
JavaScript
8
star
71

torch_mobile

Torch7 for mobile devices
C
7
star
72

vkui-benchmarks

JavaScript
7
star
73

noverify-phpstorm

NoVerify plugin for PhpStorm
Kotlin
6
star
74

superappkit-ios

Ruby
6
star
75

swc-plugin-transform-remove-imports

Rust
6
star
76

VideoPlayer-iOS

Swift
6
star
77

statshouse-go

StatsHouse client library for Go
Go
6
star
78

create-vkui-app

JavaScript
6
star
79

m3u8

Parser and generator of M3U8-playlists for Apple HLS.
Go
5
star
80

nginx-statshouse-module

StatsHouse module for nginx
C
5
star
81

statshouse-cpp

StatsHouse client library for C++
C++
5
star
82

statshouse-php

StatsHouse client library for PHP and KPHP
PHP
5
star
83

stylelint-config

TypeScript
4
star
84

statshouse-java

Java
4
star
85

modulite-example-project

This example project contains some Modulite errors, detected by IDE, PHPStan, and KPHP
PHP
4
star
86

kphp-tools

A set of independent tools to work with KPHP compiled code
JavaScript
4
star
87

kphp-snippets

Libraries written in PHP aimed to be compiled with KPHP
PHP
4
star
88

vk-mini-apps-course-frontend

TypeScript
4
star
89

graph-cache

Easy way to build and maintain persistent dependency graph for any type of files/languges
JavaScript
4
star
90

gulp-portal

JavaScript
4
star
91

sprites

Module for generate SVG sprites and PNG fallback
JavaScript
4
star
92

swc-plugin-pre-paths

Rust
3
star
93

mask-assets

AngelScript
3
star
94

mini-apps-analytics

TypeScript
3
star
95

vk-apps-currency

JavaScript
3
star
96

eslint-plugin

JavaScript
3
star
97

vk-apps-qr

VK Apps + QR demo app
JavaScript
2
star
98

ktest-script

PHP
2
star
99

mvk-mini-apps-scroll-helper

JavaScript
2
star
100

prettier-config

JavaScript
2
star