Retrofit 2 swagger响应为200,但无法从响应正文

时间:2018-06-05 13:48:34

标签: authentication retrofit swagger token

我试图通过一个昂首阔步的宁静服务获得连接并从Retrofit 2获取令牌,我得到的响应是200但无法从响应主体获取令牌

private void login() {
        Call<User> call=userClient.login("user","123","password");

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

                if(response.isSuccessful()){
                    token=response.body().getToken();
                    Toast.makeText(LoginActivity.this,token,Toast.LENGTH_SHORT).show();


                }else{
                    Toast.makeText(LoginActivity.this,"login not correct",Toast.LENGTH_SHORT).show();
                }

            }

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

                Toast.makeText(LoginActivity.this,"error",Toast.LENGTH_SHORT).show();

            }
        });
    }

1 个答案:

答案 0 :(得分:0)

像这样创建User类

 public class User {

@SerializedName("access_token")
@Expose
private String accessToken;
@SerializedName("token_type")
@Expose
private String tokenType;
@SerializedName("expires_in")
@Expose
private Integer expiresIn;

public String getAccessToken() {
return accessToken;
}

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

public String getTokenType() {
return tokenType;
}

public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}

public Integer getExpiresIn() {
return expiresIn;
}

public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}

}

然后尝试这样

token=response.body().getAccessToken();

您的改造实例应该像

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