Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi I am new to android and now I am using Retrofit for integrating the web services.

I am not understanding how to send parameters to the server using Retrofit POST request.

Please help me. Thanks.

MainActivity:-

 String url = "XXXXXXXXX/";

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


        Retrofit retrofit = new Retrofit.Builder().baseUrl(url).
                addConverterFactory(GsonConverterFactory.create()).build();

        PostInterface service = retrofit.create(PostInterface.class);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("email", "device3@gmail.com");
            jsonObject.put("password", "1234");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final String result = jsonObject.toString();

        service.getStringScalar(result).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {

                System.out.println("result is====>" + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                System.out.println("Failuere");
            }
        });
    }

PostInterface:-

public interface PostInterface {

    @POST("User/DoctorLogin")
    Call<String> getStringScalar(@Body String body);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

Make a new model class :

public class Credentials {
    private String email;
    private String password;
    public Credentials(String email, String password) {
        this.email = email;
        this.password = password;
    }
}

Then modify your interface :

public interface PostInterface {

    @POST("User/DoctorLogin")
    Call<String> getStringScalar(@Body Credentials body);
}

Then call it like this :

service.getStringScalar(new Credentials("device3@gmail.com", "1234")).enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {

            System.out.println("result is====>" + response.body());
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            System.out.println("Failuere");
        }
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...