使用Retrofit2发送POST请求中的JSON数据

20

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

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

请求的JSON:

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

响应 JSON:

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

我想将“result”发送到服务器。 - user5102362
如果后端接受字符串,则使用@Field而不是@Body。或者将您的请求转换为POJO,然后使用@Body发送。 - sushildlh
无论如何,请提供正确的解决方案,并附上一些详细的代码说明,我是一个非常初学者。 - user5102362
好的,等一下我会提供。 - user5102362
可以像这样完美地使用 RequestBody -> RequestBody body = RequestBody.create(MediaType.parse("text/plain"), text); 详细答案请参考 https://futurestud.io/tutorials/retrofit-2-how-to-send-plain-text-request-body - Kidus Tekeste
显示剩余9条评论
5个回答

20
请在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类,可以消除Retrofit中的JSON数据解析。

可以像这样完美地使用 RequestBody -> RequestBody body = RequestBody.create(MediaType.parse("text/plain"), text); 详细答案请参考 https://futurestud.io/tutorials/retrofit-2-how-to-send-plain-text-request-body - Kidus Tekeste

18
这种方法对我有效。
我的Web服务 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) {
    }
}

3
在某些情况下使用 JSONObject 可能会失败,因此建议创建自定义对象。请参考 Jake Wharton 在此处的评论 https://github.com/square/retrofit/issues/500 - Code_Yoga
7
调用JSONObject的toString()方法会因错误的序列化而失败,因为它会将"{"email":"random@gmail.com","password":"12345678"}"发送到服务器。 - soshial
@soshial,你好。我在传递JSON字符串时也遇到了500错误,请问你能帮我解决这个问题吗?谢谢。 - Vijaya Varma Lanke
.addConverterFactory(ScalarsConverterFactory.create()) 对我有效...感谢 @Jonathan - varotariya vajsi

1

从Retrofit 2+开始,使用POJO对象而不是JSON对象发送带有@Body注释的请求。如果发送了JSON对象,则请求字段将被设置为其默认值,而不是从后端应用程序发送的值。这在使用POJO对象时不会发生。


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


Retrofit2 的最佳解决方案 - Oussama Haff.

0
  1. Post请求中的Json

    val jsonObject = JSONObject()
                try {
                    jsonObject.put("name", name)
                    jsonObject.put("username", username)
                    jsonObject.put("email", email)
                    jsonObject.put("phone", phone)
                    jsonObject.put(
                        "token",
                        Prefs.getPrefInstance()!!.getValue(requireContext(), Const.TOKEN, "")
                    )
                    //                jsonObject.put("image", uploaded_image);
                    jsonObject.put("image", url)
                } catch (e: JSONException) {
                    binding.loader.visibility = View.GONE
                    e.printStackTrace()
                }
                val params = jsonObject.toString()
                val user_registering = params.toRequestBody("application/json".toMediaTypeOrNull())
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接