通过翻新获得令牌

时间:2019-03-20 15:20:50

标签: java android api http retrofit2

现在我遇到了翻新和网站API授权的问题。

我的代码基于以下内容:

How can I take token with Retrofit2 in Android Studio?

https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit#define-the-endpoints

https://github.com/codepath/android_guides/wiki/Leveraging-the-Gson-Library

这是我的MainActivity.java:

public class MainActivity extends AppCompatActivity {

public static final String BASE_URL = "https://api.some.some/v1/";

SomeAPI userClient;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

userClient  = retrofit.create(SomeAPI.class);

login();

}

private void login() {
    Auth login = new Auth("123456", "12345678");
    Call<User> call = userClient.login(login);

    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            if (response.isSuccessful()){
                Toast.makeText(MainActivity.this, response.body().getToken(), Toast.LENGTH_SHORT).show();
                token = response.body().getToken();
            }
            else {
                Toast.makeText(MainActivity.this, "Token is not truth :(", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(MainActivity.this, "error!", Toast.LENGTH_SHORT).show();
        }
    });
}

}

这是我的Some API接口:

public interface SomeAPI {

    @POST("token")
    Call<User> login(@Body Auth login);

}

这是我的Auth.java:

public class Auth {
    private String login;
    private String password;

    public Auth(String login, String password) {
        this.login = login;
        this.password = password;
    }
}

这是我的User.java:

public class User {
    private int id;
    private String email;
    private String token;

    public int getId(){
        return id;
    }

    public void setId(){
        this.id = id;
    }
    public String getEmail(){
        return  email;
    }

    public void setEmail(String email){
        this.email = email;
    }
    public String getToken(){return token;}
    public void setToken(String token){this.token = token;}
}

关于以下网站截图上的网站API:  Request

Response

主要问题是:我的代码有什么问题?为什么我无法获得令牌?

1 个答案:

答案 0 :(得分:0)

您的api需要两个属性loginpassword,并且您正在发送userpassword,请参阅Auth类更改变量名称userlogin

onResponse方法更改中

if (response.isSuccessful()){
   ...
}

if (response.code() == 201) {
    ...
}