简体   繁体   English

使用 Retrofit2 在 POST 请求中发送 JSON

[英]Sending JSON in POST request with Retrofit2

I'm using Retrofit to integrate my Web services and I do not understand how to send a JSON object to the server using a POST request.我正在使用 Retrofit 来集成我的 Web 服务,但我不明白如何使用 POST 请求将 JSON 对象发送到服务器。 I'm currently stuck, here is my code:我目前卡住了,这是我的代码:

Activity:-活动:-

@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();

}

PostInterface:-邮政接口:-

public interface PostInterface {

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

Request JSON:-请求 JSON:-

{
"email":"device3@gmail.com",
"password":"1234"
}

Response JSON:-响应 JSON:-

{
  "error": false,
  "message": "User Login Successfully",
  "doctorid": 42,
  "active": true
}

Use these in gradle在gradle中使用这些

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

Use these two POJO class ........使用这两个POJO类........

LoginData.class登录数据类

public class LoginData {

    private String email;
    private String password;

    public LoginData(String email, String password) {
        this.email = email;
        this.password = password;
    }

    /**
     *
     * @return
     * The email
     */
    public String getEmail() {
        return email;
    }

    /**
     *
     * @param email
     * The email
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     *
     * @return
     * The password
     */
    public String getPassword() {
        return password;
    }

    /**
     *
     * @param password
     * The password
     */
    public void setPassword(String password) {
        this.password = password;
    }

}

LoginResult.class登录结果类

public class LoginResult {

    private Boolean error;
    private String message;
    private Integer doctorid;
    private Boolean active;

    /**
     *
     * @return
     * The error
     */
    public Boolean getError() {
        return error;
    }

    /**
     *
     * @param error
     * The error
     */
    public void setError(Boolean error) {
        this.error = error;
    }

    /**
     *
     * @return
     * The message
     */
    public String getMessage() {
        return message;
    }

    /**
     *
     * @param message
     * The message
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     *
     * @return
     * The doctorid
     */
    public Integer getDoctorid() {
        return doctorid;
    }

    /**
     *
     * @param doctorid
     * The doctorid
     */
    public void setDoctorid(Integer doctorid) {
        this.doctorid = doctorid;
    }

    /**
     *
     * @return
     * The active
     */
    public Boolean getActive() {
        return active;
    }

    /**
     *
     * @param active
     * The active
     */
    public void setActive(Boolean active) {
        this.active = active;
    }

}

Use API like this像这样使用 API

public interface RetrofitInterface {
     @POST("User/DoctorLogin")
        Call<LoginResult> getStringScalar(@Body LoginData body);
}

use call like this ....像这样使用电话....

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("Your domain URL here")
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

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

 Call<LoginResult> call=service.getStringScalar(new LoginData(email,password));
    call.enqueue(new Callback<LoginResult>() {
                @Override
                public void onResponse(Call<LoginResult> call, Response<LoginResult> response) { 
               //response.body() have your LoginResult fields and methods  (example you have to access error then try like this response.body().getError() )

              }

                @Override
                public void onFailure(Call<LoginResult> call, Throwable t) {
           //for getting error in network put here Toast, so get the error on network 
                }
            });

EDIT:-编辑:-

put this inside the success() ....把这个放在success() ....

if(response.body().getError()){
   Toast.makeText(getBaseContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();


}else {
          //response.body() have your LoginResult fields and methods  (example you have to access error then try like this response.body().getError() )
                String msg = response.body().getMessage();
                int docId = response.body().getDoctorid();
                boolean error = response.body().getError();  

                boolean activie = response.body().getActive()();   
}

Note :- Always use POJO classes , it remove the JSON data parsing in the retrofit .注意:- 始终使用 POJO 类,它删除了改造中的 JSON 数据解析。

This way works for me这种方式对我有用

My web service我的网络服务在此处输入图片说明

Add this in your gradle将此添加到您的 gradle 中

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

Interface界面

public interface ApiInterface {

    String ENDPOINT = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

Activity活动

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

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

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.ENDPOINT)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "sample@gmail.com");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

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

i think you should now create a service generator class and after that you should use Call to call your service我认为您现在应该创建一个服务生成器类,然后您应该使用 Call 来调用您的服务

PostInterface postInterface = ServiceGenerator.createService(PostInterface.class);
Call<responseBody> responseCall =
            postInterface.getStringScalar(requestBody);

then you can use this for synchronous request and get the body of response:然后您可以将其用于同步请求并获取响应正文:

responseCall.execute().body();

and for asynchronous :对于异步:

responseCall.enqueue(Callback);

refer to link provided below for complete walkthrough and how to create ServiceGenerator :有关完整演练以及如何创建 ServiceGenerator ,请参阅下面提供的链接:

https://futurestud.io/tutorials/retrofit-getting-started-and-android-client https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

From Retrofit 2+ use POJO objects rather than a JSON Object for sending requests with @Body annotations.从 Retrofit 2+ 开始,使用 POJO 对象而不是 JSON 对象来发送带有 @Body 注释的请求。 With JSON object being sent the request fields are set to their default value than what has been sent from the app on backend.发送 JSON 对象后,请求字段设置为默认值,而不是从后端应用程序发送的值。 This won't be the case with POJO objects. POJO 对象不会出现这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM