Как добавить тело JSON в мой запрос на публикацию с помощью Retrofit? - PullRequest
0 голосов
/ 11 ноября 2019

Я пытаюсь отправить запрос POST с помощью библиотеки Retrofit.

Вот мой MarketApiCalls интерфейс и мой сетевой метод, выполняющий работу -

public interface MarketApiCalls {


    @POST("api/Search/Vendor/Multiple")
    Call<String> getVendors(
            @Query("take") int take,
            @Query("page") int page,
            @Body String json
    );
}
private void initNetworking() {
        String body = "[{ \"filters\": { \"VendorName\": { \"value\": [\"*\"], \"cretiria\": 0, \"type\": 5 } } }]"
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://search.myverte.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        marketApiCalls = retrofit.create(MarketApiCalls.class);

        Call<String> vendorsCall = marketApiCalls.getVendors(9, 0, body);
        vendorsCall.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (!response.isSuccessful()) {
                    Toast.makeText(getContext(), "Not successful", Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.d("response body", response.body());
            }

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

            }
        });
    }

Вот JSON, который мне нужно присоединить к запросу POST в качестве тела -

[{
    "filters": {
        "VendorName": { 
            "value": ["*"],
            "cretiria": 0,
            "type": 5
        }
    }
}]

Проблема в том, что я получаю код ошибки 400. Он не указывает, что тело отсутствует или повреждено, просто выдает ошибку 400, сообщая следующую ошибку -

enter image description here

Чего мне не хватает? Я подозреваю, что я не даю тело по мере необходимости.

edit -

Я пробовал следующее решение, но возникает та же ошибка -

public class VendorBodyModel {
    private Filters filters;

    public VendorBodyModel() {
    }

    public VendorBodyModel(Filters filters) {
        this.filters = filters;
    }

    public Filters getFilters() {
        return filters;
    }

    public void setFilters(Filters filters) {
        this.filters = filters;
    }
    public class Filters {
        private VendorName vendorName;

        public Filters() {
        }

        public Filters(VendorName vendorName) {
            this.vendorName = vendorName;
        }
    }

    public class VendorName {
        private String[] value;
        private int cretiria;
        private int type;

        public VendorName(String[] value, int cretiria, int type) {
            this.value = value;
            this.cretiria = cretiria;
            this.type = type;
        }

        public String[] getValue() {
            return value;
        }

        public void setValue(String[] value) {
            this.value = value;
        }

        public int getCretiria() {
            return cretiria;
        }

        public void setCretiria(int cretiria) {
            this.cretiria = cretiria;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
    }
}
public interface MarketApiCalls {


    @POST("api/Search/Vendor/Multiple")
    Call<String> getVendors(
            @Query("take") int take,
            @Query("page") int page,
            @Body VendorBodyModel bodyModel
    );
}
private void initNetworking() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://search.myverte.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        marketApiCalls = retrofit.create(MarketApiCalls.class);
        String[] array = {"*"};
        int cretiria = 5;
        int type = 0;
        VendorBodyModel.VendorName vendorName = new VendorBodyModel().new VendorName(array, 5, 0);
        VendorBodyModel.Filters filters = new VendorBodyModel().new Filters(vendorName);
        VendorBodyModel vendorBodyModel = new VendorBodyModel(filters);

        Call<String> vendorsCall = marketApiCalls.getVendors(9, 0, vendorBodyModel);
        vendorsCall.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (!response.isSuccessful()) {
                    Toast.makeText(getContext(), "Not successful", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(getContext(), "FUCKING SUCCESS!!!", Toast.LENGTH_SHORT).show();
                Log.d("response body", response.body());
            }

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

            }
        });
    }

Чего мне не хватает?

1 Ответ

1 голос
/ 11 ноября 2019

Просто создайте класс пост-модели следующим образом:


class Body {
    Filters filters;
    int parameter2;
}

class Filters {
    VendorName VendorName;
    .......
    .......
    .......
}

и используйте его следующим образом:

 @POST("api/Search/Vendor/Multiple")
    Call<String> getVendors(
            @Query("take") int take,
            @Query("page") int page,
            @Body Body json
    );

А также убедитесь, что имена полей класса Body соответствуют требуемым именам, такжене забывайте, что список или массив помечены [...], просто pojo {...}

Вот полный класс тела в Kotlin:

data class Body(
    @SerializedName("filters")
    val filters: Filters? = Filters()
)

data class Filters(
    @SerializedName("VendorName")
    val vendorName: VendorName? = VendorName()
)

data class VendorName(
    @SerializedName("value")
    val value: List<String?>? = listOf(),
    @SerializedName("cretiria")
    val cretiria: Int? = 0,
    @SerializedName("type")
    val type: Int? = 0
)
...