响应{协议= http / 1.1,代码= 400,消息=错误请求

时间:2019-05-23 05:07:28

标签: android retrofit2

我正在尝试构建一个应用程序,并希望集成一个登录API。但是响应似乎不成功。

我的MainActivity.java

...
`    package com.example.hb.loginapi;

import com.example.hb.loginapi.Login;
import com.example.hb.loginapi.ApiUtils;
import com.example.hb.loginapi.ResObj;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    String emailID;

    String password;

    Login login;

    EditText emailField;
    EditText passwordField;
    TextView loginBtn;


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


        emailField=(EditText)findViewById(R.id.enterEmail);
        passwordField=(EditText)findViewById(R.id.enterPassword);

        emailField.setText("jk@grr.la");
        passwordField.setText("Jk@12345");

        passwordField.setTransformationMethod(new PasswordTransformationMethod());

        loginBtn=(TextView)findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(this);

        login=ApiUtils.getLoginClass();
    }

    @Override
    public void onClick(View view){
        if(view.getId()==R.id.loginBtn){
            emailID=emailField.getText().toString();
             password=passwordField.getText().toString();

             if(validateLogin(emailID,password)){
                 doLogin(emailID,password);
             }
//             else{
//                 Toast.makeText(getApplicationContext(),"Username or Password Incorrect",Toast.LENGTH_LONG).show();
//             }
        }
    }

    private boolean validateLogin(String email, String password){
        if(email==null || email.trim().length()==0){
            Toast.makeText(getApplicationContext(),"Email required",Toast.LENGTH_LONG).show();
            return false;
        }
    if(password==null || password.trim().length()==0){
        Toast.makeText(getApplicationContext(),"Password required",Toast.LENGTH_LONG).show();
        return false;
    }
    return true;
}

    private void doLogin(final String email, final String password){
         Call<ResObj> call=login.loginInfo(email,password);
         call.enqueue(new Callback<ResObj>() {
             @Override
             public void onResponse(Call<ResObj> call, Response<ResObj> response) {
                 if (response.isSuccessful()) {
                     ResObj resObj = response.body();
                     if (resObj.getMessage().equals("You have successfully logged in.")) {
                         Toast.makeText(getApplicationContext(), "Successful", Toast.LENGTH_LONG).show();
                         } else {
                         Toast.makeText(getApplicationContext(), "Please provide correct data.", Toast.LENGTH_LONG).show();
                     }
                 }
             }
             @Override
             public void onFailure(Call<ResObj> call, Throwable t) {
                 Log.d("failure",t.getMessage()+"");
                 Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
             }
        });
    }
}`
...

改造登录界面。     ...     `包com.example.hb.loginapi;

import retrofit2.Call;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;

 interface Login {

   @PUT("user_login_v1/{email}/{password}")
   Call<ResObj> loginInfo(@Path("email") String email, @Path("password") String password);

}`
...

ResObj.java     ...     `包com.example.hb.loginapi;

public class ResObj {
    private String message;

    public String getMessage(){
        return message;
    }
    public void setMessage(String message){
        this.message=message;
    }
}
`
...

RetrofitClient.java     ...     `包com.example.hb.loginapi;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static Retrofit retrofit = null;





    public static Retrofit getClient(String url){


        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
//                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
`
...

APIUtils.java     ...         `包com.example.hb.loginapi;

public class ApiUtils {
    public static final String BASE_URL="http://locateaplate.projectspreview.net/WS/";

    public static Login getLoginClass(){
        return RetrofitClient.getClient(BASE_URL).create(Login.class);
    }
}`
..

我的响应JSON

  {
"settings": {
    "success": "1",
    "message": "You have successfully logged in.",
    "fields": [
        "user_id",
        "email",
        "status",
        "profile_image",
        "access_token",
        "phone",
        "user_name",
        "plate_number",
        "state_id",
        "state",
        "is_social",
        "is_notification_enabled",
        "search_report_count"
    ]
},
"data": [
    {
        "user_id": "108",
        "email": "jk@grr.la",
        "status": "Active",
        "profile_image": "http://locateaplate.projectspreview.net/public/upload/profile_images/978307200_0-20190515152207782279.png",
        "access_token": "a4e7fc783f5b56af1eb3d3e762c05468b5a1ef71c38d2a8508ef32678a99b3d0",
        "phone": "",
        "user_name": "Jack Kalsan",
        "plate_number": "ABC1234",
        "state_id": "2722",
        "state": "Abakan",
        "is_social": "",
        "is_notification_enabled": "Yes",
        "search_report_count": "69"
    }
]

}

1 个答案:

答案 0 :(得分:1)

您的界面应为

interface Login {

   @GET("user_login_v1")
   Call<ResObj> loginInfo(@Query("email") String email, @Query("password") String password);

}

响应模型为

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class ResObj{

    @SerializedName("settings")
    private Settings settings;

    @SerializedName("data")
    private List<DataItem> data;

    public void setSettings(Settings settings){
        this.settings = settings;
    }

    public Settings getSettings(){
        return settings;
    }

    public void setData(List<DataItem> data){
        this.data = data;
    }

    public List<DataItem> getData(){
        return data;
    }

    public class Settings {

        @SerializedName("success")
        private String success;

        @SerializedName("message")
        private String message;

        @SerializedName("fields")
        private List<String> fields;

        public void setSuccess(String success) {
            this.success = success;
        }

        public String getSuccess() {
            return success;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setFields(List<String> fields) {
            this.fields = fields;
        }

        public List<String> getFields() {
            return fields;
        }
    }

    public class DataItem{

        @SerializedName("user_name")
        private String userName;

        @SerializedName("search_report_count")
        private String searchReportCount;

        @SerializedName("access_token")
        private String accessToken;

        @SerializedName("profile_image")
        private String profileImage;

        @SerializedName("is_social")
        private String isSocial;

        @SerializedName("is_notification_enabled")
        private String isNotificationEnabled;

        @SerializedName("user_id")
        private String userId;

        @SerializedName("phone")
        private String phone;

        @SerializedName("plate_number")
        private String plateNumber;

        @SerializedName("state_id")
        private String stateId;

        @SerializedName("state")
        private String state;

        @SerializedName("email")
        private String email;

        @SerializedName("status")
        private String status;

        public void setUserName(String userName){
            this.userName = userName;
        }

        public String getUserName(){
            return userName;
        }

        public void setSearchReportCount(String searchReportCount){
            this.searchReportCount = searchReportCount;
        }

        public String getSearchReportCount(){
            return searchReportCount;
        }

        public void setAccessToken(String accessToken){
            this.accessToken = accessToken;
        }

        public String getAccessToken(){
            return accessToken;
        }

        public void setProfileImage(String profileImage){
            this.profileImage = profileImage;
        }

        public String getProfileImage(){
            return profileImage;
        }

        public void setIsSocial(String isSocial){
            this.isSocial = isSocial;
        }

        public String getIsSocial(){
            return isSocial;
        }

        public void setIsNotificationEnabled(String isNotificationEnabled){
            this.isNotificationEnabled = isNotificationEnabled;
        }

        public String getIsNotificationEnabled(){
            return isNotificationEnabled;
        }

        public void setUserId(String userId){
            this.userId = userId;
        }

        public String getUserId(){
            return userId;
        }

        public void setPhone(String phone){
            this.phone = phone;
        }

        public String getPhone(){
            return phone;
        }

        public void setPlateNumber(String plateNumber){
            this.plateNumber = plateNumber;
        }

        public String getPlateNumber(){
            return plateNumber;
        }

        public void setStateId(String stateId){
            this.stateId = stateId;
        }

        public String getStateId(){
            return stateId;
        }

        public void setState(String state){
            this.state = state;
        }

        public String getState(){
            return state;
        }

        public void setEmail(String email){
            this.email = email;
        }

        public String getEmail(){
            return email;
        }

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

        public String getStatus(){
            return status;
        }
    }
}

检索消息:

 ResObj resObj = response.body();
 String message=resObj.getSetting().getMessage();