使用Retrofit2在POST请求中发送JSON

时间:2016-11-26 10:29:01

标签: android json retrofit2

我正在使用Retrofit来集成我的Web服务,我不明白如何使用POST请求将JSON对象发送到服务器。我现在卡住了,这是我的代码:

的活动: -

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

请求JSON: -

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

响应JSON: -

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

4 个答案:

答案 0 :(得分:11)

这种方式对我有用

我的网络服务 enter image description here

在你的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'

<强>接口

public interface ApiInterface {

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

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

}

<强>活动

   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) {
    }
}

答案 1 :(得分:10)

在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'
  

使用这两个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;
    }

}
  

使用像这样的API

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

使用这样的电话....

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

编辑: -

  

将此内容放入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()();   
}

注意: - 始终使用POJO类,它会在改造中删除JSON数据解析。

答案 2 :(得分:1)

我认为你现在应该创建一个服务生成器类,之后 你应该用Call来打电话给你的服务

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

然后你可以将它用于同步请求并得到响应体:

responseCall.execute().body();

和异步:

responseCall.enqueue(Callback);

请参阅下面提供的链接以获取完整的演练以及如何创建ServiceGenerator:

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

答案 3 :(得分:0)

从Retrofit 2+开始,使用POJO对象而不是JSON对象发送带有@Body批注的请求。发送JSON对象后,请求字段的值将设置为默认值,而不是后端应用程序发送的值。 POJO对象不是这种情况。