0

Новичок в Retrofit. Хочу отправить GET-запрос серверу и получить ответ. Отправляю запрос, в onResponse получаю значение переменной count из PhotoResponse, равное 0. Значит, где-то что-то делаю не так, потому что, отправляя запрос из браузера, получаю нужный ответ.

Пример запроса, который нужно отправить:

 https://api.vk.com/method/photos.get?owner_id=-130670107&album_id=wall&rev=1&access_token=API_KEY&v=5.101

Во время исполнения кода никаких ошибок не возникает.


MainActivity.java

NetworkService.getInstance()
                .getVkApi()
                .getWallPhotos("-130670107", "wall", 1, BuildConfig.VKApiKey, "5.101")
                .enqueue(new Callback<PhotoResponse>() {
                    @Override
                    public void onResponse(@NonNull Call<PhotoResponse> call, @NonNull Response<PhotoResponse> response) {
                        PhotoResponse photo = response.body();

                        text = photo.getCount() + "\n";
                    }

                    @Override
                    public void onFailure(@NonNull Call<PhotoResponse> call, @NonNull Throwable t) {

                        text= "Error occurred while getting request!";
                        t.printStackTrace();
                    }
                });

NetworkService.java

public class NetworkService {
    private static NetworkService mInstance;
    private static final String BASE_URL = "https://api.vk.com/method/";
    private Retrofit mRetrofit;

    private NetworkService() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static NetworkService getInstance() {
        if (mInstance == null) {
            mInstance = new NetworkService();
        }
        return mInstance;
    }

    public VkApiInterface getVkApi() {
        return mRetrofit.create(VkApiInterface.class);
    }
}

VkApiInterface.java

public interface VkApiInterface {
    @GET("photos.get?")
    public Call<PhotoResponse> getWallPhotos(@Query("owner_id") String owner, @Query("album_id") String album, @Query("rev") int rev,@Query("access_token") String token, @Query("v") String version);
}

Пример получаемого JSON

{
"response": {
"count": 41,
"items": [{
"id": 247648259,
"album_id": -7,
"owner_id": -1,
"user_id": 100,
"sizes": [{
"type": "s",
"url": "https://sun9-2.us...1621/s_f15991c2.jpg",
"width": 0,
"height": 0
}, {
"type": "m",
"url": "https://sun9-2.us...1621/m_4228adaf.jpg",
"width": 0,
"height": 0
}, {
"type": "x",
"url": "https://sun9-2.us...1621/x_46426f27.jpg",
"width": 0,
"height": 0
}],
"text": "",
"date": 1302516221
}, {
"id": 248743686,
"album_id": -7,
"owner_id": -1,
"user_id": 100,
"sizes": [{
"type": "s",
"url": "https://sun9-7.us...2/-5/s_80529ba4.jpg",
"width": 0,
"height": 0
}, {
"type": "m",
"url": "https://sun9-7.us...2/-5/m_5fe2d21f.jpg",
"width": 0,
"height": 0
}, {
"type": "x",
"url": "https://sun9-7.us...2/-5/x_06bffe46.jpg",
"width": 0,
"height": 0
}],
"text": "",
"date": 1302712950
}]
}
}

PhotoResponse.java

public class PhotoResponse {
    @SerializedName("count")
    @Expose
    private int count;
    @SerializedName("items")
    @Expose
    private List<PhotoItem> items = new ArrayList<PhotoItem>();

    public PhotoResponse(){}

    public PhotoResponse(int count, List<Item> items){
        this.count = count;
        this.items = items;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }
}

PhotoItem.java

    public class PhotoItem {
    @SerializedName("id")
    @Expose
    private int id;

    @SerializedName("album_id")
    @Expose
    private int albumId;

    @SerializedName("owner_id")
    @Expose
    private int ownerId;

    @SerializedName("user_id")
    @Expose
    private int userId;

    @SerializedName("sizes")
    @Expose
    private List<PhotoSize> photoSizes = new ArrayList<PhotoSize>();

    @SerializedName("text")
    @Expose
    private String text;

    @SerializedName("date")
    @Expose
    private String date;

    public PhotoItem(){}

    public PhotoItem(int id, int albumId, int ownerId, int userId, List<PhotoSize> sizes, String text, String date){
        this.id = id;
        this.albumId = albumId;
        this.ownerId = ownerId;
        this.userId = userId;
        this.photoSizes = sizes;
        this.text = text;
        this.date = date;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAlbumId() {
        return albumId;
    }

    public void setAlbumId(int albumId) {
        this.albumId = albumId;
    }

    public int getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(int ownerId) {
        this.ownerId = ownerId;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public List<PhotoSize> getPhotoSizes() {
        return photoSizes;
    }

    public void setPhotoSizes(List<PhotoSize> photoSizes) {
        this.photoSizes = photoSizes;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

PhotoSize.java

public class PhotoSize {
    @SerializedName("type")
    @Expose
    private String type;

    @SerializedName("url")
    @Expose
    private String url;

    @SerializedName("width")
    @Expose
    private int width;

    @SerializedName("height")
    @Expose
    private int height;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }
}
9
  • а в логах что-то есть?
    – Andrew
    10 авг 2019 в 16:01
  • 2
    Попробуйте убрать ? из @GET("photos.get?")
    – ЮрийСПб
    10 авг 2019 в 16:39
  • Вы уверены что "Программа не попадает ни в onResponse, ни в onFailure"? Что-то по коду не видно как вы это определили. Может вы выводите переменную text в TextView где-то ниже по коду? Тогда на момент вывода запрос ещё не обработан - перенесите вывод внутрь методов колбэка (onResponse и onFailure).
    – woesss
    10 авг 2019 в 18:42
  • @AndrewGoroshko нет.
    – Daria
    11 авг 2019 в 9:40
  • @ЮрийСПб убирала, но ничего не изменилось.
    – Daria
    11 авг 2019 в 9:40

1 ответ 1

3

Ошибка у вас в том, что неправильный тип данных указан. Вы указываете PhotoResponse, тогда как он суть лишь вложенный объект ответа ВК. Вам надо его обернуть в ещё один класс, в котором будет всего одно поле с типом PhotoResponse и именем response. Именно его надо указать в качестве возвращаемого значения.

public class VkPhotosResponse {
    public PhotoResponse response;
}
public interface VkApiInterface {
    @GET("photos.get")
    public Call<VkPhotosResponse> getWallPhotos(@Query("owner_id") String owner, @Query("album_id") String album, @Query("rev") int rev,@Query("access_token") String token, @Query("v") String version);
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.