【发布时间】:2018-08-24 02:10:55
【问题描述】:
我尝试通过 POST json {"email":"test@example.com","password":"test"} 接收令牌。在邮递员中它可以工作: Postman request。 我尝试在 Android Studio 中做同样的事情。 我创建类 Token:
public class Token {
@SerializedName("token")
@Expose
public String token;
}
还有类APIclient
class APIClient {
private static Retrofit retrofit = null;
static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("http://mybaseurl.com/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
和接口APIInterface:
interface APIInterface {
@POST("/authenticate")
Call<Token> getLoginResponse(@Body AuthenticationRequest request);
}
和类 AuthenticationRequest:
public class AuthenticationRequest {
String email;
String password;
}
在MainActivity的onCreate中:
apiInterface = APIClient.getClient().create(APIInterface.class);
authenticationRequest.email="test@example.com";
authenticationRequest.password="test";
getTokenResponse();
这是我的 getTokenResponse 方法:
private void getTokenResponse() {
Call<Token> call2 = apiInterface.getLoginResponse(authenticationRequest);
call2.enqueue(new Callback<Token>() {
@Override
public void onResponse(Call<Token> call, Response<Token> response) {
Token token = response.body();
}
@Override
public void onFailure(Call<Token> call, Throwable t) {
call.cancel();
}
});
}
这就是我在 Logcat 中看到的:
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> POST http://mybaseurl.com/authenticate http/1.1
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Type: application/json; charset=UTF-8
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Length: 46
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: {"email":"test@example.com","password":"test"}
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> END POST (46-byte body)
你能告诉我我做错了什么吗?每次我想通过 GET 方法从服务器获取信息时,我都需要提供令牌。 如何在 Android 代码中接收和保存令牌?
【问题讨论】:
-
您是否从标头获取/发送令牌?
-
在 GET 方法中我在标头授权中发送令牌
-
我已经发布了答案。请看一下。
标签: android post retrofit2 restful-authentication