shivam
shivam

Reputation: 475

Retrofit 2.0 post request

Hello I am trying to implement Post request using Retrofit 2.0

My Question is that show Should I write in onResponse so as to get data by taking input from the user or manually.

Thank you

Upvotes: 1

Views: 485

Answers (2)

IgorGanapolsky
IgorGanapolsky

Reputation: 26814

onResponse is called AFTER the request completes. You wouldn't be asking for user's input in this reverse order (unless you are doing multiple requests or chaining them). So you should already have user's input PRIOR to making the Retrofit request.

So your onResponse callback is where you process the http response:

    @Override
    public void onResponse(Call<List<Card>> call, Response<List<Card>> response) {
        processResponse(response.body());
    }

But before you send the request (and receive the response), you can add form data to your POST request, you can do something like:

@POST("/api/Cards")
Call<List<Card>> createCards(@Body List<Card> cards,
        // Sort the cards using a query string param
        @Query("sort") String contractAccount),
        // Set a group id parameter as the replacement block
        @Path("id") int groupId);

Upvotes: 0

sushildlh
sushildlh

Reputation: 9056

for post method you have to use @Body tags in interface

@POST("/api/Cards")
Call<List<Card>> createCards(@Body List<Card> cards);

and call from activity

Card card=new Card();
card.setId(20);
card.setTitle("New Cards");
card.setMessage("New Launched cards");

List<Card> cards=new List<Card>();
cards.add(card);
Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestApi requestApi = retrofit.create(RequestApi.class);
    mCardsRequest = requestApi.createCards(cards);
    mCardsRequest.enqueue(new Callback<List<Card>>() {
        @Override
        public void onResponse(Call<List<Card>> call, Response<List<Card>> response) {
            ** what should I add here to post data **   
        }

        @Override
        public void onFailure(Call<List<Card>> call, Throwable t) {
            //
        }
    });

Upvotes: 1

Related Questions