Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

android - Retrofit2: Sending POST request with String request

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

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

1 Reply

0 votes
by (71.8m points)

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");
        }
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...