Retrofit POST Request with body parameters android

14,023

Solution 1

First you need to create request( POJO Class)

public class FeedbackRequest {
   public String email;
   public String feedback;
}

when you call sendFeedbackRequest() pass the FeedbackRequest like below"

FeedbackRequest req = new FeedbackRequest();
req.email= "email";
req.feedback= "feedback"
sendFeedbackRequest(req)

after that your sendFeedbackRequest() should be like this

  private void sendFeedbackRequest(FeedbackRequest request){
      API.request().sendFeedback(request).enqueue(new Callback<String>() {
      @Override
      public void onResponse(Call<String> call, Response<String> response) {
        goToMainActivity();
      }

      @Override
      public void onFailure(Call<String> call, Throwable t) {
        Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
    }
});

And your retrofit request should be like this,

@FormUrlEncoded
@POST("api/android-feedback")
@Headers({"Content-Type: application/json", "Authorization: F31daaw313415"})
Call<String> sendFeedback(@Body FeedbackRequest request);

Now it should work. feel free to ask anything.

Solution 2

You are using a Gson converter factory. It might be easier to create a single object that represents your body, and use that instead of all individual parameters. That way, you should be able to simple follow along with the examples on the Retrofit website.enter link description here There are also many site that let you generate your Plain Old Java Objects for you, like this one:

E.g. your Api call:

@POST("api/android-feedback")
Call<String> sendFeedback(@Body FeedbackBody feedback);    

And your FeedbackBody class:

public class FeedbackBody{
    private final String email;
    private final String feedback;

    public FeedbackBody(String email, String feedback){
        this.email = email;
        this.feedback = feedback;
    }
}
Share:
14,023

Related videos on Youtube

Kristiyan Varbanov
Author by

Kristiyan Varbanov

Graduated student from the Technical University of Varna with Computer Systems and Technology Bachelor degree. Self motivated person, ready to learn and prosper along it's way to the peak of professionalism. I am android developer with 2+ years experience. I have 4 completed android project.

Updated on June 04, 2022

Comments

  • Kristiyan Varbanov
    Kristiyan Varbanov almost 2 years

    I need to execute post request with retrofit but i have a problem which i can't understand very well. Before trying with code i tested api call with Postman and request look like this:

    capture1 enter image description here

    Here is my android code:

    public class API {
    
    private static <T> T builder(Class<T> endpoint) {
    
        return new Retrofit.Builder()
                .baseUrl(Utils.API_BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(endpoint);
    }
    public static AllRequests request() {
        return builder(AllRequests.class);
    }
    }
    

    EDIT request:

    @POST("api/android-feedback")
    @Headers({"Content-Type: application/x-www-form-urlencoded", "Authorization: F#@3FA@#Rad!@%!2s"})
    Call<String> sendFeedback(@Body FeedbackBody body);
    

    FeedbackBody:

    public class FeedbackBody{
    private final String email;
    private final String feedback;
    
    public FeedbackBody(String email, String feedback){
        this.email = email;
        this.feedback = feedback;
    }
    

    }

    And finally i construct the request and wait for response, the problem is that i receive message in onFail method

       private void sendFeedbackRequest(){
        API.request().sendFeedback(new FeedbackBody("[email protected]", "test feedback").enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                goToMainActivity();
            }
    
            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
            }
        });
    

    EDIT: Still not working.. i think i figure it out where can be the problem, because server side wait for simple POST request without Json formatting, i think Retrofit use JSON formatting by default, and if i send POST request and format Body parameters with JSON the server will fail to parse my request, is there any chance to send simple POST request like at POSTMAN without formatting with JSON ?

    • Php api wait request to be send like this:

    $_POST['feedback'] = 'blabla'; $_POST['email'] = 'blabla..';

    and if he receive Json format request can't parse it and because of that i receive fail response.

  • Kristiyan Varbanov
    Kristiyan Varbanov almost 5 years
    I tried your answer but still not work properly, you can check my edit question, i will be glad if you can help me with.
  • Kristiyan Varbanov
    Kristiyan Varbanov almost 5 years
    I tried your answer but still not work properly, you can check my edit question, i will be glad if you can help me with.
  • Sajith
    Sajith almost 5 years
    change your sendFeedbackRequest(final String feedback, final String email) to sendFeedbackRequest(FeedbackBody body)
  • Kristiyan Varbanov
    Kristiyan Varbanov almost 5 years
    i change it, but again i send JSON format and server can't parse it, is it any possibility to send them raw POST without formatting it as JSON.
  • Sajith
    Sajith almost 5 years
    can you update your current code(edited) related to this issue to a google doc and paste the link here
  • Sajith
    Sajith almost 5 years
    you are doing it wrong. check sendFeedbackRequest() function in your code and my answer
  • Sajith
    Sajith almost 5 years