【问题标题】:Unable to post data using Retrofit as raw JSON无法使用 Retrofit 作为原始 JSON 发布数据
【发布时间】:2020-10-12 17:17:13
【问题描述】:

我正在尝试使用来自原始 json 的 retrofit2 将数据发布到服务器,但服务器没有响应。进度条继续加载,但服务器没有响应。

我的服务器正在发送下面的 json 对象作为成功消息:

{
"status": "Success",
"statusCode": "S001",
"loginResponse": {
    "authenticationStatus": false,
    "sessionid": null,
    "errorDescription": null,
    "predictionStatus": null,
    "predictionPercentage": null,
    "predictionPercentageA": null,
    "predictionPercentageB": null,
    "predictionPercentageC": null
 }
}

我只想检查status 是否为Success,因此我在POJO 类LoginResponse 下进行了检查。

登录响应

public class LoginResponse {

@SerializedName("status")
String status;

public LoginResponse(){

}

public LoginResponse(String status) {
    this.status = status;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}
}

下面是我的代码:

ApiService.class

public interface ApiService {

@POST("userLoginVerification")
Call<LoginResponse> getResponse(@Body JsonObject body);
}

MainActivity.class

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

    login = findViewById(R.id.login);
    email = findViewById(R.id.email);
    pwd = findViewById(R.id.pwd);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final ProgressDialog prg = new ProgressDialog(MainActivity.this);
            prg.setCancelable(false);
            prg.setMessage("Logging in...");
            prg.show();

            String str1 = email.getText().toString();
            String str2 = pwd.getText().toString();

            if(str1.equals("")){

                prg.dismiss();
                TastyToast.makeText(getApplicationContext(),"Enter email",TastyToast.LENGTH_SHORT,
                        TastyToast.ERROR).show();
            }
            else if(str2.equals("")){

                prg.dismiss();
                TastyToast.makeText(getApplicationContext(),"Enter password",TastyToast.LENGTH_SHORT,
                        TastyToast.ERROR).show();
            }
            else{

                Retrofit retrofit = RetrofitClient.getInstance();
                ApiService apiService = retrofit.create(ApiService.class);

                JsonObject jsonObject= new JsonObject();
                jsonObject.addProperty("userId",str1);
                jsonObject.addProperty("password",str2);

                Call<LoginResponse> call = apiService.getResponse(jsonObject);

                call.enqueue(new Callback<LoginResponse>() {
                    @Override
                    public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {

                       try{
                            JSONObject jsonObject1 = new JSONObject(resp);

                            String str = jsonObject1.getString("status");

                            if(str.equals("Success")){

                                prg.dismiss();
                                email.setText("");
                                pwd.setText("");
                            }
                           }
                          catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

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

                        TastyToast.makeText(getApplicationContext(),t.getMessage(),TastyToast.LENGTH_SHORT,
                                   TastyToast.ERROR).show();
                    }
                });

            }
        }
    });
  }

执行上述代码时服务器没有响应。请有人告诉我我做错了什么。任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: java android retrofit2 rx-java2


    【解决方案1】:

    public void onResponse(Call&lt;LoginResponse&gt; call, Response&lt;LoginResponse&gt; response)

    不要在onResponse 中创建JSONObjectresponse.body() 为您提供 LoginResponse 对象。使用该对象获取状态。如果活动或片段没有被破坏,则在onResponseonFailure 之后立即关闭进度条。

    【讨论】:

    • 这意味着我应该删除 try-catch 块并简单地使用 resp 字符串。
    • 是的。使用response
    【解决方案2】:

    在您的 ApiService 中

    @FormUrlEncoded
    @POST("userLoginVerification")
    Call<User> getResponse(@FieldMap HashMap<String, String> data);
    

    还有HashMap

    HashMap<String, String> map = new HashMap<>();
            map.put("userId", "theUserId");
            map.put("password", "thePassword");
    

    另外,一个大问题是您的回复格式不正确

    { "status": "Success" }
    

    但是在ApiService 你期望服务器返回一个用户! 您必须更改 getResponse 返回类型以匹配服务器响应格式。

    还有一个问题

    if (response.equals("Success"))
    

    这个条件永远不会成立,因为response 不是String,你不能用这种方式检查相等性。你应该使用response.body()

    【讨论】:

    • 嘿,我已经在上面添加了完整的服务器响应,并相应地更改了我的 ApiService 返回类型,请检查我的代码并让我知道它仍然没有验证用户有什么问题。
    • 我认为您的数据发送不正确。你应该在你的getResponse 方法中使用@FieldMap(就像我的回答一样)。如果你想使用@Body 你应该为getResponse 参数创建一个POJO 类
    猜你喜欢
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2017-06-17
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多