http 400误差在Retrofit 2中调用URL时



在我的活动中,我使用EditTexts从用户那里获取电子邮件和密码,然后将它们添加到JSONOBJECT变量中。我将此变量转换为字符串,并将此字符串作为我的帖子请求中的主体发送到API。但是,无效响应主体我遇到了400个错误。这是相关的代码:

登录活动:

email = findViewById(R.id.edt_login_email);
password = findViewById(R.id.edt_login_password);
linearLayout = findViewById(R.id.linearlayout_login);
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://api.thinghub.io/v0/").addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
final WebService webService = retrofit.create(WebService.class);
final Button button = findViewById(R.id.btn_login_login);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        emailToString = email.getText().toString();
        passwordToString = password.getText().toString();
        JsonObject userDetail = new JsonObject();
        userDetail.addProperty("mail", emailToString);
        userDetail.addProperty("password", passwordToString);
        Log.d(TAG, userDetail.toString());
        Call <JsonResponse> call = webService.login(userDetail.toString());
        call.enqueue(new Callback < JsonResponse > () {
            @Override
            public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
                Log.d(TAG, String.valueOf(response.code()));
                Log.d(TAG, String.valueOf(response.body()));
                Log.d(TAG, String.valueOf(response.headers()));
                if (response.isSuccessful()) {
                    Toast.makeText(LoginActivity.this, "Succsessful login", Toast.LENGTH_SHORT).show();
                    // token = response.body().getUuid();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    SharedPreferences userDetails = (LoginActivity.this).getSharedPreferences("userdetails", MODE_PRIVATE);
                    SharedPreferences.Editor edit = userDetails.edit();
                    edit.putString("mail", emailToString);
                    edit.putString("token", token);
                    edit.apply();
                    startActivity(intent);
                } else {
                    TextView mTitle = new TextView(LoginActivity.this);
                    mTitle.setText("NO RESPONSE GET");
                    mTitle.setGravity(Gravity.CENTER);
                    mTitle.setPadding(8, 8, 8, 8);
                    new MaterialAlertDialogBuilder(LoginActivity.this)
                        .setCustomTitle(mTitle)
                        .setMessage("username or password is wrong")
                        .setPositiveButton("try again", null)
                        .show();
                }
            }
        });

WebService接口:

public interface WebService {
    @POST("token")
    Call<JsonResponse> login(@Body String body);
}

jsonresponse类:

public class JsonResponse {
    private String string;
    public JsonResponse(String string) {
        this.string = string;
    }
    public String getString() {
        return string;
    }
    public void setString(String string) {
        this.string = string;
    }
}

我得到此日志输出:

D/UDJ: {"mail":"ghasemi@test.com","password":"123123"}
D/UDJ: 400
D/UDJ: null

为什么会发生?

您必须像下面的

那样调用翻新
JsonObject userDetail = new JsonObject();
userDetail.addProperty("mail", emailToString);
userDetail.addProperty("password", passwordToString);
Log.d(TAG, userDetail.toString());
Call <JsonResponse> call = webService.login(userDetail);
call.enqueue(new Callback<JsonResponse> () {
   @Override
   public void onResponse(Call<JsonResponse> call, Response <JsonResponse> response) {
    Log.d(TAG, String.valueOf(response.code()));
    Log.d(TAG, String.valueOf(response.body()));
    Log.d(TAG, String.valueOf(response.headers()));
    if (response.isSuccessful()) {
     Toast.makeText(LoginActivity.this, "Succsessful login", Toast.LENGTH_SHORT).show();
     // token = response.body().getUuid();
     Intent intent = new Intent(LoginActivity.this, MainActivity.class);
     SharedPreferences userDetails = (LoginActivity.this).getSharedPreferences("userdetails", MODE_PRIVATE);
     SharedPreferences.Editor edit = userDetails.edit();
     edit.putString("mail", emailToString);
     edit.putString("token", token);
     edit.apply();
     startActivity(intent);
    } else {

     TextView mTitle = new TextView(LoginActivity.this);
     mTitle.setText("NO RESPONSE GET");
     mTitle.setGravity(Gravity.CENTER);
     mTitle.setPadding(8, 8, 8, 8);
     new MaterialAlertDialogBuilder(LoginActivity.this)
      .setCustomTitle(mTitle)
      .setMessage("username or password is wrong")
      .setPositiveButton("try again", null)
      .show();

    }
   }

接口是:

public interface WebService {
       @POST("token")
       Call<JsonResponse> login(@Body JsonObject body);
}

@hengameh,我相信您遇到的错误是因为您将请求对象发送为字符串。您想要的是将数据类发送到改装,然后改造将其转换为JSON的工作。创建一个请求类。

class LoginRequest{
String mail;
String password;}

现在而不是

 JsonObject userDetail = new JsonObject();
userDetail.addProperty("mail", emailToString);
userDetail.addProperty("password",passwordToString);

添加

LoginRequest userDetail = new LoginRequest();
        userDetail.mail = emailToString;
        userDetail.password = passwordToString;

修改接口为

public interface WebService {
@POST("token")
Call<JsonResponse> login(@Body LoginRequest body);
}

和呼叫应为

Call<JsonResponse> call = webService.login(userDetail);

在翻新中,默认情况下没有用于字符串的转换器。这就是为什么您没有发送适当的请求。但是,由于您添加了GSON转换器,因此可以将userDetail JSONOBJECT直接传递到login()函数:

JsonObject userDetail = new JsonObject();
userDetail.addProperty("mail", "ghasemi@test.com");
userDetail.addProperty("password", "123123");
Log.d(TAG, userDetail.toString());
Call<JsonResponse> call = webService.login(userDetail);
call.enqueue(new Callback<JsonResponse>() {
    @Override
    public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
        if (response.isSuccessful()) {
            Log.e(TAG, "Successful login");
            JsonResponse jsonResponse = response.body();
            // Use login data here...
        } else {
            Log.e(TAG, "Unsuccessful login");
        }
    }
    @Override
    public void onFailure(Call<JsonResponse> call, Throwable t) {
        Log.e(TAG, "Failure!");
    }
});

如果您仍然想将车身作为字符串提供,则需要将标量连接器库添加到您的应用程序gradle:

implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'

...然后将其添加到您的翻新实例中,如下所示:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.thinghub.io/v0/")
    .addConverterFactory(ScalarsConverterFactory.create())
    .addConverterFactory(GsonConverterFactory.create())
    .build();

现在,您的字符串将在您的请求中成功添加为主体。


您在两种情况下都需要这些POJO类:

jsonresponse.java

public class JsonResponse {
    @SerializedName("uuid")
    @Expose
    private String uuid;
    @SerializedName("user")
    @Expose
    private String user;
    @SerializedName("createdAt")
    @Expose
    private String createdAt;
    @SerializedName("expiresAt")
    @Expose
    private String expiresAt;
    @SerializedName("detail")
    @Expose
    private Detail detail;
    @SerializedName("lastAccessAt")
    @Expose
    private Object lastAccessAt;
    @SerializedName("suspendedOrgs")
    @Expose
    private List<Object> suspendedOrgs = null;
    public String getUuid() {
        return uuid;
    }
    public void setUuid(String uuid) {
        this.uuid = uuid;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getCreatedAt() {
        return createdAt;
    }
    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }
    public String getExpiresAt() {
        return expiresAt;
    }
    public void setExpiresAt(String expiresAt) {
        this.expiresAt = expiresAt;
    }
    public Detail getDetail() {
        return detail;
    }
    public void setDetail(Detail detail) {
        this.detail = detail;
    }
    public Object getLastAccessAt() {
        return lastAccessAt;
    }
    public void setLastAccessAt(Object lastAccessAt) {
        this.lastAccessAt = lastAccessAt;
    }
    public List<Object> getSuspendedOrgs() {
        return suspendedOrgs;
    }
    public void setSuspendedOrgs(List<Object> suspendedOrgs) {
        this.suspendedOrgs = suspendedOrgs;
    }
}

细节java

public class Detail {
    @SerializedName("ip-address")
    @Expose
    private String ipAddress;
    @SerializedName("user-agent")
    @Expose
    private String userAgent;
    @SerializedName("x-forwarded-for")
    @Expose
    private String xForwardedFor;
    @SerializedName("accept-language")
    @Expose
    private Object acceptLanguage;
    @SerializedName("visitor-country")
    @Expose
    private String visitorCountry;
    public String getIpAddress() {
        return ipAddress;
    }
    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }
    public String getUserAgent() {
        return userAgent;
    }
    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }
    public String getXForwardedFor() {
        return xForwardedFor;
    }
    public void setXForwardedFor(String xForwardedFor) {
        this.xForwardedFor = xForwardedFor;
    }
    public Object getAcceptLanguage() {
        return acceptLanguage;
    }
    public void setAcceptLanguage(Object acceptLanguage) {
        this.acceptLanguage = acceptLanguage;
    }
    public String getVisitorCountry() {
        return visitorCountry;
    }
    public void setVisitorCountry(String visitorCountry) {
        this.visitorCountry = visitorCountry;
    }
}

最新更新