@Chesterfield25

Как отправить Post запрос в json используя retrofit2?

Помогите с POST запросом retrofit. Ни как не даётся для изучения! При использование примера ниже и нажатии на кнопку в приложение выдаёт ошибку:

E/MainActivity: onResponse: null

5f7ecf8aafca4074265893.png

До меня дошло суть частичной ошибки:
У меня два класса один в котором данные для отправки ApiClients, другой в котором данные для получения Todo. В activity_main две кнопки одна для получения данных вторая для отправки. Но для получения данных Todo мне нужно сперва отправить ApiClients. Проще говоря эти два класса не взаимодействуют между собой. Подскажите как этот не до код собрать воедино что бы он был работоспособный?

Суть задачи: отправка пользователю определённой сумы на баланс при нажатие на кнопку!
Вся документация API с которым я работаю https://faucetpay.io/page/api-documentation
В Todo классе данные для получения в ApiClients данные для отправки.

Адрес для отправки: https://faucetpay.io/api/v1/send

Пример данных для отправки:

КЛЮЧ: api_key=74445766sd9c0ebe19ca067471be1b41be398f5c
СУМА: amount=50
КОШЕЛЁК: to=MQYSDrNwiJxr1VmLiJHNqaMtJeNon5NUGn
ВАЛЮТА: currency=LTC


Пример ответа на запрос:

{
    "status": 200,
    "message": "OK",
    "rate_limit_remaining": 9.99780024,
    "currency": "BTC",
    "balance": "8673047351",
    "balance_bitcoin": "86.73047351",
    "payout_id": 109,
    "payout_user_hash": "c448e31098a8dfb48248f7e2374e77674bb90925"
}


Структура приложения:

activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GET TODOS"
        android:onClick="getTodos"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POST TODOS"
        android:onClick="postTodos"/>

</LinearLayout>


MainActivity класс
ublic class MainActivity extends AppCompatActivity {


    private static final String TAG = "MainActivity";
    ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        apiInterface = ApiClient.getClient().create(ApiInterface.class);

    }

    public void getTodos(View view) {

        Call<List<Todo>> call = apiInterface.getTodos();
        call.enqueue(new Callback<List<Todo>>() {
            @Override
            public void onResponse(Call<List<Todo>> call, Response<List<Todo>> response) {
                Log.e(TAG, "onResponse: " + response.body());
            }

            @Override
            public void onFailure(Call<List<Todo>> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getLocalizedMessage());
            }
        });

    }

    public void postTodos(View view) {

        ApiClients apiClients = new ApiClients("74445766sd9c0ebe19ca067471be1b41be398f5c", 50, "MQYSDrNwiJxr1VmLiJHNqaMtJeNon5NUGn", "LTC");
        Call<ApiClients> apiClientsPostCall = apiInterface.postApiClients(apiClients);
        apiClientsPostCall.enqueue(new Callback<ApiClients>() {
            @Override
            public void onResponse(Call<ApiClients> call, Response<ApiClients> response) {
                Log.e(TAG, "onResponse: " + response.body());
            }

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

            }
        });

    }


}


Todo класс
public class Todo {

    private int status;
    private String message;
    private double rate_limit_remaining;
    private String currency;
    private double balance;
    private double balance_bitcoin;
    private int payout_id;
    private String payout_user_hash;

    public Todo(int status, String message, double rate_limit_remaining, String currency, double balance, double balance_bitcoin, int payout_id, String payout_user_hash) {
        this.status = status;
        this.message = message;
        this.rate_limit_remaining = rate_limit_remaining;
        this.currency = currency;
        this.balance = balance;
        this.balance_bitcoin = balance_bitcoin;
        this.payout_id = payout_id;
        this.payout_user_hash = payout_user_hash;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public double getRate_limit_remaining() {
        return rate_limit_remaining;
    }

    public void setRate_limit_remaining(double rate_limit_remaining) {
        this.rate_limit_remaining = rate_limit_remaining;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public double getBalance_bitcoin() {
        return balance_bitcoin;
    }

    public void setBalance_bitcoin(double balance_bitcoin) {
        this.balance_bitcoin = balance_bitcoin;
    }

    public int getPayout_id() {
        return payout_id;
    }

    public void setPayout_id(int payout_id) {
        this.payout_id = payout_id;
    }

    public String getPayout_user_hash() {
        return payout_user_hash;
    }

    public void setPayout_user_hash(String payout_user_hash) {
        this.payout_user_hash = payout_user_hash;
    }


    @Override
    public String toString() {
        return "Todo{" +
                "status=" + status +
                ", message='" + message + '\'' +
                ", rate_limit_remaining=" + rate_limit_remaining +
                ", currency='" + currency + '\'' +
                ", balance=" + balance +
                ", balance_bitcoin=" + balance_bitcoin +
                ", payout_id=" + payout_id +
                ", payout_user_hash='" + payout_user_hash + '\'' +
                '}';
    }
}


ApiClient класс
public class ApiClient {

    private static final String BASE_URL = "https://faucetpay.io/api/v1/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}


ApiClients класс
public class ApiClients {

    private String api_key;
    private int amount;
    private String to;
    private String currency;

    public ApiClients(String api_key, int amount, String to, String currency) {
        this.api_key = api_key;
        this.amount = amount;
        this.to = to;
        this.currency = currency;
    }

    public String getApi_key() {
        return api_key;
    }

    public void setApi_key(String api_key) {
        this.api_key = api_key;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    @Override
    public String toString() {
        return "ApiClients{" +
                "api_key='" + api_key + '\'' +
                ", amount=" + amount +
                ", to='" + to + '\'' +
                ", currency='" + currency + '\'' +
                '}';
    }
}


ApiInterface интерфейс
public interface ApiInterface {

    @GET("/send")
    Call<List<Todo>> getTodos();

    @POST("/send")
    Call<ApiClients> postApiClients(@Body ApiClients apiClients);
}
  • Вопрос задан
  • 768 просмотров
Пригласить эксперта
Ответы на вопрос 1
@red-barbarian
что бросается в глаза
"https://faucetpay.io/api/v1/" сделать "https://faucetpay.io/api/v1"
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы