Giter VIP home page Giter VIP logo

vk-java-sdk's Introduction

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

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-api</artifactId>
        <version>2.0.9</version>
    </dependency>
</dependencies>

Gradle:

dependencies {
    compile group: 'org.slf4j', name: 'slf4j-api', version: '2.0.9'
}

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.20.0</version>
    </dependency>
    
    <!-- Log4j API and Core implementation required for binding -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.20.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.20.0</version>
    </dependency>
</dependencies>

Gradle:

dependencies {
    //Binding for Log4J -->
    compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.20.0'
    
    //Log4j API and Core implementation required for binding
    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.20.0'
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.20.0'
}

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.

vk-java-sdk's People

Contributors

alebabai avatar altager avatar anatoliys avatar aotd1 avatar apiwoman avatar dikkini avatar jarviscraft avatar johnspade avatar jvmusin avatar kokorin avatar martintomac avatar mkfl3x avatar mobyman avatar pale-emperor avatar rusgaz avatar smilesdc avatar substanceof avatar thelegioncrazy avatar tsivarev avatar vast-nectarine avatar wtlgo avatar yurybandarchuk16 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vk-java-sdk's Issues

Error when i try getting posts from id=1

GetResponse getResponse = vk.wall().get().ownerId(1).count(100).execute();

I get:

com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216) ~[gson-2.6.2.jar:?]
at com.google.gson.Gson.fromJson(Gson.java:879) ~[gson-2.6.2.jar:?]
at com.google.gson.Gson.fromJson(Gson.java:944) ~[gson-2.6.2.jar:?]
at com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:85) [sdk-0.2.0.jar:?]

Full JSON here: https://gist.github.com/7Dump/e22da453b6dbae18c274bf62336e19ce

Неправильно переопределены hashCode() и equals()

В дочерних классах не учитываются переменные из класса предка. К примеру в классе UserFull не учитываются такие переменные как id, sex и другие которые находятся не в UserFull, а в классах User и UserMin, из-за этого не правильно работают такие коллекции как HashSet. И это по всей SDK наблюдается.

https://pp.vk.me/c836723/v836723400/7243/o6P0j96zhis.jpg

Uploading photos with upload().photoWall(...)

I don't know, maybe it should be so, but if I try to upload some file as photo and this file don't have extension, server returns an exception:

com.vk.api.sdk.exceptions.ApiParamException: One of the parameters specified was missing or invalid (100): One of the parameters specified was missing or invalid: photos_list is invalid

So, if in this code (it's Kotlin) remove ".$type" (where type is "png" or "jpg") from filename, uploadResponse.photo will be empty and VK API would return exception.

val file = File("D:/temp/${url.hashCode()}.$type") //if remove .$type here
file.writeBytes(WebUtils.getBytes(url)) //works fine, returns ByteArray from some given URL, I checked this one manually
val serverResponse = vk.photos().getWallUploadServer(actor).groupId(groupId).execute()
val uploadResponse = vk.upload().photoWall(serverResponse.uploadUrl, file).file(file).execute()
//when exception will be thrown, next line outputs something like this: photo=[],604726,1da25ca91786709b0e833df3ca45e9b3,136741752
logger.info("photo=${uploadResponse.photo},${uploadResponse.server},${uploadResponse.hash},$groupId")
val photo = vk.photos().saveWallPhoto(actor, uploadResponse.photo)
        .server(uploadResponse.server)
        .hash(uploadResponse.hash)
        .groupId(groupId)
        .execute()[0] //here is an exception at com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:73)

Gson exception

.oauth().groupAuthorizationCodeFlow(APPLICATION_ID, APPLICATION_SECRET, groupRedirectUrl, code).execute()

IllegalArgumentException occurred : @JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.

play.exceptions.JavaExecutionException: @JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.

Caused by: java.lang.IllegalArgumentException: @JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.
	at com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory.getTypeAdapter(JsonAdapterAnnotationTypeAdapterFactory.java:64)
	at com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory.create(JsonAdapterAnnotationTypeAdapterFactory.java:47)
	at com.google.gson.Gson.getAdapter(Gson.java:416)
	at com.google.gson.Gson.fromJson(Gson.java:878)
	at com.google.gson.Gson.fromJson(Gson.java:944)
	at com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:85)

MessagesSendQuery#attachment doesn't mention access_key

Documentation of
MessagesSendQuery#attachment doesn't mention that access_key should be included for sending attachments that links to the private media.
I think that information should be reflected in documentation, because VK API will just ignore attachment parameter, if it has no access_key.
If one will try to send message with only private attachment (i.e. without message body) without access_key then server will respond that there is no message parameter (which is optional if attachment present), which is very confusing.

Option to disable logger

I'am not using log4j, and I dont want to use it.
So I always get error in stdout:
SLF4J: The following set of substitute loggers may have been accessed SLF4J: during the initialization phase. Logging calls during this SLF4J: phase were not honored. However, subsequent logging calls to these SLF4J: loggers will work as normally expected. SLF4J: See also http://www.slf4j.org/codes.html#substituteLogger SLF4J: org.webjars.WebJarExtractor ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
Maybe we should to add option to disable sdk logging?

Ошибка "Invalid JSON" при запросе постов со стены

Добрый день!
При проверке выполнения issue #60 обнаружил, что при ранее корректно работавшем вызове теперь возникает ошибка.
Вызов SDK:
GetResponse response = vk.wall().get(actor).ownerId(owner).execute();

Ошибка возникает при вызове кода в com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:85).

Сама ошибка (выжимка):
2017-04-08 17:33:24 INFO HttpTransportClient:158 - Request: https://api.vk.com/method/wall.get 113 2017-04-08 17:33:24 ERROR ApiRequest:87 - Invalid JSON: {"тут_полный_ответный_JSON} com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected NUMBER but was BEGIN_OBJECT at path $.items[0].views

Судя по всему, ошибка возникает из-за того, что в атрибуте views ответного JSON находится не число, а вложенный атрибут count, который и содержит число просмотров.

Также отмечу, что, например, для получения числа лайков из объекта WallpostFull, требуется выполнить getLikes().getCount(), а для получения просмотров сейчас доступен только метод getViews() (без getCount()). Вызвать getViews().getCount() сейчас невозможно.

Ошибка (полностью):
2017-04-08 17:33:24 INFO HttpTransportClient:158 - Request: https://api.vk.com/method/wall.get 113 2017-04-08 17:33:24 ERROR ApiRequest:87 - Invalid JSON: {"тут_полный_ответный_JSON} com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected NUMBER but was BEGIN_OBJECT at path $.items[0].views at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220) ~[gson-2.8.0.jar:?] at com.google.gson.Gson.fromJson(Gson.java:887) ~[gson-2.8.0.jar:?] at com.google.gson.Gson.fromJson(Gson.java:952) ~[gson-2.8.0.jar:?] at com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:85) [sdk-0.5.0.jar:?] at тут_мои_классы Caused by: java.lang.IllegalStateException: Expected NUMBER but was BEGIN_OBJECT at path $.items[0].views at com.google.gson.internal.bind.JsonTreeReader.nextInt(JsonTreeReader.java:241) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:243) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.TypeAdapters$7.read(TypeAdapters.java:235) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129) ~[gson-2.8.0.jar:?] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220) ~[gson-2.8.0.jar:?] ... 11 more

error on users.get method

Hi!
I've got error on users.get method.

        List<String> personIds = Arrays.asList(
                "50554801",
                "150534158",
                "429527209",
                "377312665");
        UsersGetQuery query = apiClient.users().get(actor)
                .fields(fields) //all existing fields 
                .userIds(personIds); 

I think that element "exports": [] from profile id 377312665 is wrong for your deserializer.

[26/07/17 05:59:39:039 MSK] ERROR client.ApiRequest: Invalid JSON: {"response":[{"id":150534158,"first_name":"Вася","last_name":"Пупкин","sex":2,"nickname":"","domain":"id150534158","screen_name":"id150534158","bdate":"29.2.1904","city":{"id":1708920,"title":"Bujumbura"},"country":{"id":46,"title":"Бурунди"},"photo_50":"https://pp.userapi.com/c626121/v626121158/66df3/sFUeIaMgn4U.jpg","photo_100":"https://pp.userapi.com/c626121/v626121158/66df2/aoRqWA7olJM.jpg","photo_200":"https://pp.userapi.com/c626121/v626121158/66df1/q2VePmfMRQI.jpg","photo_max":"https://pp.userapi.com/c626121/v626121158/66df1/q2VePmfMRQI.jpg","photo_200_orig":"https://pp.userapi.com/c626121/v626121158/66def/_DwGY0bE3tU.jpg","photo_400_orig":"https://pp.userapi.com/c626121/v626121158/66df0/6LnuBKqkySM.jpg","photo_max_orig":"https://pp.userapi.com/c626121/v626121158/66df0/6LnuBKqkySM.jpg","photo_id":"150534158_456240031","has_photo":1,"has_mobile":1,"is_friend":0,"friend_status":0,"online":1,"wall_comments":1,"can_post":0,"can_see_all_posts":0,"can_see_audio":1,"can_write_private_message":0,"can_send_friend_request":1,"mobile_phone":"пркнмвк","home_phone":"гншщзрн","site":"https://vk.com/app638461_150534158 ","status":"","last_seen":{"time":1501081159,"platform":7},"crop_photo":{"photo":{"id":456240031,"album_id":-6,"owner_id":150534158,"photo_75":"https://pp.userapi.com/c626121/v626121158/66dc4/64Gam-EWpB4.jpg","photo_130":"https://pp.userapi.com/c626121/v626121158/66dc5/KS1TbFs6w4M.jpg","photo_604":"https://pp.userapi.com/c626121/v626121158/66dc6/4etMCsccmTQ.jpg","width":404,"height":500,"text":"","date":1488571191,"post_id":1046},"crop":{"x":0.000000,"y":0.000000,"x2":100.000000,"y2":100.000000},"rect":{"x":0.000000,"y":4.400000,"x2":100.000000,"y2":85.200000}},"verified":0,"followers_count":3026,"blacklisted":0,"blacklisted_by_me":0,"is_favorite":0,"is_hidden_from_feed":0,"common_count":0,"occupation":{"type":"university","id":508725,"name":"University of Oxford"},"career":[{"company":"Парварешгои ватан","country_id":30,"city_id":705,"from":1955,"until":2017,"position":"султан"}],"university":508725,"university_name":"University of Oxford","faculty":2188341,"faculty_name":"Mathematical Institute","graduation":1945,"home_town":"Хузенванштауперде, Атлантида...","relation":3,"personal":{"political":1,"langs":["भोजपुरी","保安语","ܐܪܡܝܐ","ဗမာစာ","ਪੰਜਾਬੀ","ދިވެހި","日本語"],"religion":"Иудаизм","people_main":4,"life_main":8,"smoking":5,"alcohol":5},"interests":"...идиотизм, дурошлёпство, глупость, воровство, рукоблудство, прелюбодеяние ......так же люблю нюхать клей, глотать колёса, бухать, курить траву, врать, валять дурака и нести всякую чушь, иногда напинать кому-нибудь под сраку","music":"Надежда Бабкина, Иосиф Кобзон, Толибджон Курбанханов, Алла Пугачёва, Борис Моисеев, Жанна Агузарова, Коля Басков, Азис, якутские мантры","activities":"......колдовство вуду, заклинания, целительство, контакт с инопланетянами, общение с духами, ...... легко снимаю, а также навожу: порчу, зглаз, проклятие на 700 поколений, понос, запор, чесотку, целюлит, геморой, тугодумство, косоглазие, криворожие, жопорукость ............... запросто чудеса, вызов цунами, землетрясений, мировых кризисов, революций, ..........подрабатываю директором мировой закулисы, осуществляю руководство мировым жидо-масонским заговором","movies":"Красная шапочка, Белоснежка, Карлсон, Терминатор, Красавица и чудовище, Рембо, Колобок, Хищник, Спящая красавица, Молчание ягнят, Курочка Ряба","tv":"поле чудес, Играй гармонь, Жди меня, дом-2, улица сезам, давай поженимся, прямая линия с Владимиром Путиным","books":"","games":"","universities":[{"id":508725,"country":46,"city":1708920,"name":"University of Oxford","faculty":2188341,"faculty_name":"Mathematical Institute","graduation":1945,"education_form":"Очное отделение","education_status":"Доктор наук"}],"schools":[],"about":"","relatives":[{"id":-746196292,"type":"grandchild","name":"Путин"},{"id":-432277180,"type":"grandchild","name":"Медведев"},{"id":-971850195,"type":"child","name":"Карлсон"},{"id":-503115669,"type":"child","name":"Колобок"},{"id":-103365772,"type":"parent","name":"Волк"},{"id":-972576267,"type":"parent","name":"Красная Шапочка"},{"id":-835782072,"type":"sibling","name":"Дед Мороз"},{"id":-797298178,"type":"sibling","name":"Санта-Клаус"},{"id":-552731090,"type":"sibling","name":"Конёк-Горбунёк"},{"id":-929883888,"type":"sibling","name":"Домовёнок Кузя"},{"id":-306596816,"type":"sibling","name":"Винни-Пух"},{"id":-451422758,"type":"sibling","name":"Синдбад-Мореход"},{"id":-979329774,"type":"sibling","name":"Змей Горыныч"},{"id":-110248029,"type":"sibling","name":"Сивка-Бурка"},{"id":-917769856,"type":"sibling","name":"Кащей Бессмертный"},{"id":-572363152,"type":"sibling","name":"Гендальф Серый"},{"id":-616150415,"type":"grandparent","name":"Водяной"},{"id":-868763707,"type":"grandparent","name":"Леший"},{"id":-331129566,"type":"grandparent","name":"Баба Яга"},{"id":-160484676,"type":"grandparent","name":"Снежная Королева"},{"id":-245697929,"type":"sibling","name":"Кот-В-Сапогах"}],"quotes":""},{"id":429527209,"first_name":"Денис","last_name":"Прайм","sex":2,"nickname":"","domain":"id429527209","screen_name":"id429527209","city":{"id":55,"title":"Иваново"},"country":{"id":1,"title":"Россия"},"photo_50":"https://pp.userapi.com/c837326/v837326209/3f681/_lwZITQBosc.jpg","photo_100":"https://pp.userapi.com/c837326/v837326209/3f680/bjgk3ZD5Y0s.jpg","photo_200":"https://pp.userapi.com/c837326/v837326209/3f67f/v4J6QxD_zaE.jpg","photo_max":"https://pp.userapi.com/c837326/v837326209/3f67f/v4J6QxD_zaE.jpg","photo_200_orig":"https://pp.userapi.com/c837326/v837326209/3f67d/POgBYQFtT0c.jpg","photo_400_orig":"https://pp.userapi.com/c837326/v837326209/3f67e/_0lqw3xdz4w.jpg","photo_max_orig":"https://pp.userapi.com/c837326/v837326209/3f67e/_0lqw3xdz4w.jpg","photo_id":"429527209_456239017","has_photo":1,"has_mobile":1,"is_friend":0,"friend_status":0,"online":0,"wall_comments":1,"can_post":1,"can_see_all_posts":1,"can_see_audio":1,"can_write_private_message":1,"can_send_friend_request":1,"mobile_phone":"+7 (930) 330-25-03","home_phone":"+7 (4932) 26-25-03","skype":"Fix37","site":"https://fix37.ru","status":"Честный ремонт цифровой техники в Иваново!","last_seen":{"time":1501012714,"platform":1},"crop_photo":{"photo":{"id":456239017,"album_id":-6,"owner_id":429527209,"photo_75":"https://pp.userapi.com/c837326/v837326209/3f672/ossiJGuHtbM.jpg","photo_130":"https://pp.userapi.com/c837326/v837326209/3f673/2uzyS6_TlG4.jpg","photo_604":"https://pp.userapi.com/c837326/v837326209/3f674/8pqkLHU_omY.jpg","photo_807":"https://pp.userapi.com/c837326/v837326209/3f675/N3yW4hLeoRM.jpg","photo_1280":"https://pp.userapi.com/c837326/v837326209/3f676/MQ1LPy_9xbM.jpg","photo_2560":"https://pp.userapi.com/c837326/v837326209/3f677/jzknsCUT54s.jpg","width":1680,"height":1680,"text":"","date":1495194002,"post_id":1},"crop":{"x":3.270000,"y":3.270000,"x2":96.670000,"y2":96.670000},"rect":{"x":6.950000,"y":0.000000,"x2":100.000000,"y2":93.050000}},"verified":0,"followers_count":0,"blacklisted":0,"blacklisted_by_me":0,"is_favorite":0,"is_hidden_from_feed":0,"common_count":1,"occupation":{"type":"work","id":107493446,"name":"Сервисный центр ООО "Прайм-Сервис" Иваново."},"career":[{"group_id":107493446,"country_id":1,"city_id":55,"from":2012,"position":"Директор"}],"university":0,"university_name":"","faculty":0,"faculty_name":"","graduation":0,"home_town":"Иваново","relation":0,"personal":{"political":8,"religion":"Православие","life_main":6,"smoking":3,"alcohol":3},"interests":"Цифровая техника.","music":"","activities":"Участник программы "Честный Ремонт".","movies":"","tv":"","books":"","games":"","universities":[],"schools":[],"about":"Ремонт и обслуживание ноутбуков и компьютеров, телефонов и планшетов, фотоаппаратов, телевизоров и прочей цифровой техники в Иваново.","relatives":[],"quotes":""},{"id":50554801,"first_name":"Вася","last_name":"Пупкин","sex":2,"nickname":"","domain":"id50554801","screen_name":"id50554801","bdate":"10.12.1994","city":{"id":122,"title":"Рязань"},"country":{"id":1,"title":"Россия"},"photo_50":"https://pp.userapi.com/c626219/v626219801/4b9cd/D5DWVRNy2k0.jpg","photo_100":"https://pp.userapi.com/c626219/v626219801/4b9cc/Z6EqyueyK9Y.jpg","photo_200":"https://pp.userapi.com/c626219/v626219801/4b9cb/YWJfJdW2lmw.jpg","photo_max":"https://pp.userapi.com/c626219/v626219801/4b9cb/YWJfJdW2lmw.jpg","photo_200_orig":"https://pp.userapi.com/c626219/v626219801/4b9c9/NRoMmsc9tDk.jpg","photo_400_orig":"https://pp.userapi.com/c626219/v626219801/4b9ca/tqAJvaefCXg.jpg","photo_max_orig":"https://pp.userapi.com/c626219/v626219801/4b9ca/tqAJvaefCXg.jpg","photo_id":"50554801_423056089","has_photo":1,"has_mobile":1,"is_friend":0,"friend_status":0,"online":0,"wall_comments":1,"can_post":0,"can_see_all_posts":0,"can_see_audio":1,"can_write_private_message":1,"can_send_friend_request":1,"site":"www.ru","status":"За ВВС!!!","last_seen":{"time":1501064316,"platform":4},"crop_photo":{"photo":{"id":423056089,"album_id":-6,"owner_id":50554801,"photo_75":"https://pp.userapi.com/c626219/v626219801/1bc27/rwp0Sf4Z3q0.jpg","photo_130":"https://pp.userapi.com/c626219/v626219801/1bc28/r9otX15ihP8.jpg","photo_604":"https://pp.userapi.com/c626219/v626219801/1bc29/flA-0KKeh78.jpg","photo_807":"https://pp.userapi.com/c626219/v626219801/1bc2a/fuuodTUhX9E.jpg","photo_1280":"https://pp.userapi.com/c626219/v626219801/1bc2b/9FGo4k7eW4M.jpg","width":1280,"height":720,"text":"","date":1468429828,"post_id":154},"crop":{"x":22.660000,"y":0.000000,"x2":78.910000,"y2":100.000000},"rect":{"x":10.000000,"y":10.000000,"x2":89.720000,"y2":89.720000}},"verified":0,"followers_count":21,"blacklisted":0,"blacklisted_by_me":0,"is_favorite":0,"is_hidden_from_feed":0,"common_count":0,"occupation":{"type":"work","name":"Диван"},"career":[{"company":"Диван","country_id":219,"city_id":1956288,"from":1989,"position":"Бездельник"}],"university":772,"university_name":"РГРТУ","faculty":183522,"faculty_name":"Факультет вычислительной техники","graduation":2013,"home_town":"Рязань","relation":0,"personal":{"political":1,"religion":"да","people_main":2,"life_main":4,"smoking":1,"alcohol":5},"interests":"Пивас, вобла","music":"Техно","activities":"Бещдеятельность","movies":"Страх и ненависть в Лас-Вегасе","tv":"Новости","books":"Стивен Кинг, Гарри Гаррисон","games":"Настольные прятки","universities":[{"id":772,"country":1,"city":122,"name":"РГРТУ","faculty":183522,"faculty_name":"Факультет вычислительной техники","chair":1659662,"chair_name":"Информационной безопасности","graduation":2013,"education_form":"Очное отделение","education_status":"Студент (специалист)"},{"id":772,"country":1,"city":122,"name":"РГРТУ","faculty":183522,"faculty_name":"Факультет вычислительной техники","chair":192020,"chair_name":"Кафедра электронных вычислительных машин","graduation":2011,"education_form":"Очно-заочное отделение","education_status":"Студент (бакалавр)"}],"schools":[{"id":"36880","country":1,"city":122,"name":"Школа №49","year_from":1997,"year_to":2007,"year_graduated":2007,"class":"а"}],"about":"Я здесь, я там, я всегда...","relatives":[{"id":55257209,"type":"sibling"}],"quotes":"I think I may have hit upon the perfect formula of swill gin. You pour six jiggers of gin, and you drink it while staring at a picture of Lorenzo Schwartz, the inventor of vermouth. (С) Benjamin Franklin "Hawkeye" Pierce"},{"id":377312665,"first_name":"Иван","last_name":"Иванов","sex":2,"nickname":"","domain":"ii43204","screen_name":"ii43204","bdate":"9.2.1993","timezone":3,"photo_50":"https://pp.userapi.com/c626119/v626119665/22245/yevkacE6wRU.jpg","photo_100":"https://pp.userapi.com/c626119/v626119665/22244/5KO-WSNF3L8.jpg","photo_200":"https://pp.userapi.com/c626119/v626119665/22243/3Ff8X4KQbis.jpg","photo_max":"https://pp.userapi.com/c626119/v626119665/22243/3Ff8X4KQbis.jpg","photo_200_orig":"https://pp.userapi.com/c626119/v626119665/22243/3Ff8X4KQbis.jpg","photo_max_orig":"https://pp.userapi.com/c626119/v626119665/22243/3Ff8X4KQbis.jpg","photo_id":"377312665_427138949","has_photo":1,"has_mobile":1,"is_friend":0,"friend_status":0,"online":1,"online_mobile":1,"wall_comments":1,"can_post":1,"can_see_all_posts":1,"can_see_audio":1,"can_write_private_message":1,"can_send_friend_request":1,"mobile_phone":"","home_phone":"","site":"","status":"","last_seen":{"time":1501081178,"platform":1},"exports":[],"crop_photo":{"photo":{"id":427138949,"album_id":-6,"owner_id":377312665,"photo_75":"https://pp.userapi.com/c626119/v626119665/2223c/vQQtxvsWznI.jpg","photo_130":"https://pp.userapi.com/c626119/v626119665/2223d/1fgpNGkGjjQ.jpg","photo_604":"https://pp.userapi.com/c626119/v626119665/2223e/RiYR8dOndIw.jpg","width":225,"height":225,"text":"","date":1470215519,"post_id":2},"crop":{"x":5.330000,"y":5.330000,"x2":94.220000,"y2":94.220000},"rect":{"x":0.000000,"y":0.000000,"x2":100.000000,"y2":100.000000}},"verified":0,"followers_count":3,"blacklisted":0,"blacklisted_by_me":0,"is_favorite":0,"is_hidden_from_feed":0,"common_count":1,"occupation":{"type":"work","id":22468706,"name":"NASA | НАСА | Космос | Астрономия"},"career":[{"group_id":22468706,"position":"Директор по развитию"}],"university":0,"university_name":"","faculty":0,"faculty_name":"","graduation":0,"home_town":"","relation":0,"interests":"","music":"","activities":"","movies":"","tv":"","books":"","games":"","universities":[],"schools":[],"about":"","relatives":[{"id":-233343506,"type":"sibling","name":"Василий Иванов"}],"quotes":""}]}
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at path $[3].exports
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:952)
at com.vk.api.sdk.client.ApiRequest.executeWithoutRetry(ApiRequest.java:103)
at com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:66)

Access Token for Users

Guys, is this true that Access Token for a user has an expiration time of 24 hours and it needs to be requested through Authorization Flow every day again and again?

HttpTransportClient doesn't support proxy

It's not possible to use library over proxy.

The only thing is needed to implement:
RequestConfig requestConfig = RequestConfig.custom()./*blah blah blah*/.setProxy(new HttpHost(hostname, port)).build();

Thanks.

Поле offset в методе Wall.getComments не существует

Пытался получить комментарии к посту через offset и count, казалось бы, ничего необычного:

apiClient.wall()
    .getComments(actor, post_id)
    .ownerId(-owner_id)
    .offset(0) 
    .count(1000)
    .execute().getItems();

Проблема:
.offset(0) // IDEA подкрашивает эту строку красным цветом, так как метод offset(int) отсутствует в классе WallGetCommentsQuery

версия 0.3.4

OkHttp support

Maybe we should add okhttp support? It's mush better than apache

Enum for user's sex

It would be more convinient to use an enum for sex field, not simple integer value.

Wrong field types in LinksItem

When fetching group with field links, deserialization fails because of name and editTitle fields in LinksItem which are Integers instead of Strings.

Ошибка парсинга поста с с геотегом

При получении поста, в котором есть геотег ко всему посту происходит ошибка парсинга.
Парсер ожидает, что поле country - число, вместо этого в поле строка.

Пост: https://vk.com/mamin_peterburg?w=wall-79272609_15336
JSON:
fb07ee62bfc857ce630828ee2308ed45

ошибка при вызове gson.fromJson(response, responseClass) в классе abstract class ApiRequest

try { return gson.fromJson(response, responseClass); } catch (JsonSyntaxException e) { LOG.error("Invalid JSON: " + textResponse, e); throw new ClientException("Can't parse json response"); }

Caused by: java.lang.NumberFormatException: For input string: "Россия"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[?:1.8.0_31]
at java.lang.Integer.parseInt(Integer.java:580) ~[?:1.8.0_31]

Actor id, wall

Если использовать GroupActor и постить через client.wall(), то постится на стену аккаунта, а не группы.
Быстро пройдя по дереву вызовов обнаружил, что в конструкторе WallPostQuery не хватает
ownerId(actor.getId());

Field 'company' is missing in com.vk.api.sdk.objects.users.Career

In documentation (https://vk.com/dev/objects/user):

информация о карьере пользователя. Объект, содержащий следующие поля:
group_id (integer) — идентификатор сообщества (если доступно, иначе company);
company (string) — название компании (если доступно, иначе group_id);
country_id (integer) — идентификатор страны;
city_id (integer) — идентификатор города (если доступно, иначе city_name);
city_name (string) — название города (если доступно, иначе city_id);
from (integer) — год начала работы;
until (integer) — год окончания работы;
position (string) — должность.

In code (https://github.com/VKCOM/vk-java-sdk/blob/master/sdk/src/main/java/com/vk/api/sdk/objects/users/Career.java):

@SerializedName("group_id")
private Integer groupId;

@SerializedName("country_id")
private Integer countryId;

@SerializedName("city_id")
private Integer cityId;

@SerializedName("from")
private Integer from;

@SerializedName("until")
private Integer until;

@SerializedName("position")
private String position;

CallBack API

Добрый день. Интересуюсь нововведением в ВК, конкретно CallBack API.
Не понимаю один момент в документации

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

Откуда появился httpRequest? Нужно делать реализовывать свой http сервер?

Не получить список друзей

Собираю запрос для получения друзей с полем "пол".

Запрос
List<UserXtrLists>friends = vk.friends().get(actor).unsafeParam("fields", "sex").execute();

Пишет, что
incompatible types: GetResponse cannot be converted to List<UserXtrLists>

В какой объект можно скинуть массив друзей?

Ошибка с парсингом friends.getMutual с параметром target_uids

Согласно документации friends.getMutual с параметром target_uids возвращает список из id, common_friends и common_count.

Пример кода, вызвавшего ошибку с парсингом json'а: vkApiClient.friends().getMutual(userActor).targetUids(ids).execute();
Где VkApiClient vkApiClient; UserActor userActor; List<Integer> ids;

Сама ошибка:
SEVERE: Invalid JSON: {"response":[{"id":something,"common_friends":[something,something],"common_count":something}]} com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected NUMBER but was BEGIN_OBJECT at path $[0]

Используемая версия: 0.4.3

No method groupAuthorizationCodeFlow under OAuth method

This example doesn't work

AuthGroupResponse authResponse = vk.oauth()
.groupAuthorizationCodeFlow(APP_ID, CLIENT_SECRET, REDIRECT_URI, code, groupId)
.execute();

GroupActor actor = new GroupActor(authResponse.get(), authResponse.getAccessToken());

Newsfeed search cause an exception

vk.newsfeed().search().q(request).execute()

java.lang.IllegalArgumentException: class com.vk.api.sdk.objects.video.VideoFiles declares multiple JSON fields named mp_240
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:170)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.Gson.fromJson(Gson.java:886)
at com.google.gson.Gson.fromJson(Gson.java:952)
at com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:85)
at com.thesis.VKDataSource.searchPost(VKDataSource.java:50)
at com.thesis.VKDataSourceTest.testSearch(VKDataSourceTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Bring back the upload component of the Audio API

According to the official VK dev portal the methods that deal with uploading audio files are still working.

Existing methods for the audio section will be unavailable for calling, except for methods regarding audio file uploads.

Therefore, I suggest to bring the audio upload component back.
Here are the commits that removed the audio upload functionality.
f12e5cb
9917ad8

put info into exceptions

It's weird to see
if (response.getStatusCode() != 200) { throw new ClientException("Internal API server error"); }
during debugging. It would be much much better if you'll try to throw some information about the error. Maybe there are some troubles with different API response on different requests, but is it possible to make some (not so crutch) solution like this:
what I am talking about

Problems with WebSocket streaming client in new Gradle project

I try to build your stream example from front page. I make new empty Gradle project and add a simple class with single main method.

After resolving all imports/handling exceptions I got Cannot access org.acynchttpclient.ws.WebSocket on the build I get
Error:(48, 23) java: cannot access org.asynchttpclient.ws.WebSocket class file for org.asynchttpclient.ws.WebSocket not found

I use Intelij IDEA 2017.1.4 (latest version on this moment) Ultimate and Community Editions. Also same thing happen on Ubuntu 16.04 and macOS.

Here is my code. But I suppose that the problem here may be in underlying SDK dependencies.

import com.vk.api.sdk.objects.streaming.responses.GetServerUrlResponse;
import com.vk.api.sdk.streaming.clients.StreamingEventHandler;
import com.vk.api.sdk.streaming.clients.VkStreamingApiClient;
import com.vk.api.sdk.streaming.clients.actors.StreamingActor;
import com.vk.api.sdk.streaming.objects.StreamingCallbackMessage;

import java.util.concurrent.ExecutionException;

public class SdkTest {
    public static void main(String[] args){
        //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 = null;
        try {
            getServerUrlResponse = vkClient.streaming().getServerUrl(actor).execute();
        } catch (ApiException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        StreamingActor streamingActor = new StreamingActor(getServerUrlResponse.getEndpoint(), getServerUrlResponse.getKey());

        try {
            streamingClient.stream().get(streamingActor, new StreamingEventHandler() {
                @Override
                public void handle(StreamingCallbackMessage message) {
                    System.out.println(message);
                }
            }).execute();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Post to group wall throws unauthorized

I try to make post on group wall using this code:

TransportClient transportClient = new HttpTransportClient();
VkApiClient client = new VkApiClient(transportClient);
Actor actor = new GroupActor(GROUP_ID, GROUP_TOKEN);
client.wall().post(actor).message("Hello world").execute();

but this throws unauthorized exception:

[http-apr-8080-exec-4] ERROR com.vk.api.sdk.client.ApiRequest - API error
com.vk.api.sdk.exceptions.ApiAuthException: User authorization failed (5): User authorization failed: method is unavailable with group auth.

This is group id, and access token for group I get from it manage page.
What i'm doing wrong?

Error execute

What have:
ERROR com.vk.api.sdk.client.ApiRequest - Invalid JSON: {"response":31}
com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject but was com.google.gson.JsonPrimitive

What do:
JsonElement response = vk.execute().storageFunction(actor, "getMessageCount")
.unsafeParam("user_id", idPersonField.getText())
.execute();

return API.messages.getHistory({"count": 0, "user_id": Args.user_id}).count;

Something wrong with README.md

As you can see on attached screenshot, LATEST_VERSION contains wrong symbol in Maven dependency and also it is not automatically replaced with proper version (which I guess should be replaced here)
2017-07-04 17 03 25

Unknown (28): Application authorization failed: access_token has expired

Добрый день, написал вопрос в поддержку VK, меня отправили сюда, сказали нужна помощь гуру :-)
Суть проблемы:
Создал приложение (id 6116692). Пытаюсь авторизироваться с использованием сервисного ключа, как показано в документации, в ответ получаю: Application authorization failed: access_token has expired.

Использую SDK "com.vk.api" % "sdk" % "0.5.6"

Пример кода (Scala):

package ru.restream.vkexample

import com.vk.api.sdk.client.{Lang, VkApiClient}
import com.vk.api.sdk.client.actors.ServiceActor
import com.vk.api.sdk.httpclient.HttpTransportClient
import com.vk.api.sdk.queries.users.UserField

object Main extends App {

val APP_ID = 6116692 //из настроек приложения
val CLIENT_SECRET = "MBY8G8U41uyD0OszSrbD" //из настроек приложения

val transportClient = HttpTransportClient.getInstance()
val vk = new VkApiClient(transportClient)

val authRequest = vk.oauth
.serviceClientCredentialsFlow(APP_ID,CLIENT_SECRET)
.execute

val serviceActor = new ServiceActor(APP_ID,CLIENT_SECRET,authRequest.getAccessToken)

val users = vk.users
.get(serviceActor)
.userIds("1")
.fields(UserField.VERIFIED, UserField.SEX)
.lang(Lang.EN)
.execute

}

Консоль выводит:
Exception in thread "main" com.vk.api.sdk.exceptions.ApiException: Unknown (28): Application authorization failed: access_token has expired.
at com.vk.api.sdk.exceptions.ExceptionMapper.parseException(ExceptionMapper.java:257)
at com.vk.api.sdk.client.ApiRequest.executeWithoutRetry(ApiRequest.java:91)
at com.vk.api.sdk.client.ApiRequest.execute(ApiRequest.java:66)
at ru.restream.vkexample.Main$.delayedEndpoint$ru$restream$vkexample$Main$1(Main.scala:29)
at ru.restream.vkexample.Main$delayedInit$body.apply(Main.scala:11)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:378)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at ru.restream.vkexample.Main$.main(Main.scala:11)
at ru.restream.vkexample.Main.main(Main.scala)

Что делаю не так?
Спасибо

Missing fields related to Groups

Group: "has_photo", "invited_by";
GroupFull: "is_hidden_from_feed", "can_upload_doc", "place", "public_date_label", "ban_info".

Field "deactivated" should be in Group.

Also missing option "COVER" in GroupField enum.

Field "id" in Group is String instead of Integer.

Примитивы вместо объектов

Используйте примитивы вместо объектов! Long -> long, Integer -> int, Boolean -> boolean и т. д.!
Примитивы быстрее объектов в очень много раз!

Can't build project

Can you help me fix that?

No such property: ossrhUsername for class: org.gradle.api.publication.maven.in
ternal.ant.DefaultGroovyMavenDeployer

Access denied (15): Access denied: user deactivated

Добрый день,
Делаю запрос друзей пользователя (всех друзей с использованием ServiceActor), у которого в друзьях есть заблокированные аккаунты

val setIds = vk.friends().get(actor).userId(userId).execute().getItems.asScala.map(_.toInt).toSet

в итоге получаю исключение

Exception in thread "main" com.vk.api.sdk.exceptions.ApiAccessException: Access denied (15): Access denied: user deactivated

Соответственно весь запрос падает. Вопрос, как получить id всех друзей в таком случае?

Спасибо

allowMessagesFromGroup

public MessagesAllowMessagesFromCommunityQuery(VkApiClient client, UserActor actor, int groupId) { super(client, "messages.allowMessagesFromCommunity", OkResponse.class); accessToken(actor.getAccessToken()); groupId(groupId); }
but the method is messages.allowMessagesFromGroup

Реализовать работу с Streaming API через SDK

Добрый день!

В конце прошлого месяца было анонсировано открытие публичного бета-тестирования Streaming API, а также конкурс на проекты с использованием Streaming API .

Было бы круто иметь реализацию работы с Streaming API в Java SDK. Уверен, это существенно бы упростило работу с ним.

P.S. Не сомневаюсь, что поддержка Streaming API в Java SDK уже запланирована, однако я решил завести Issue по аналогии с #60 т.к. в #60 фича с доступом к счётчику просмотров была реализована только после заведения issue. Не знаю, совпадение это или нет.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.