我正在使用Retrofit 2制作一个Android应用程序。我的REST Api都是使用Liferay编写的。现在在Liferay中,我所看到的是,要访问Web服务,我们需要先进行身份验证。所以我已经像这样进行了身份验证:
http://test:q1w2e3r4@192.168.0.110:8080/liferay-portlet/api/secure/jsonws/
Liferay有自己的用户认证方法,我们已经进行了重写。我用Postman检查了Web服务调用,它正常工作。
URL:http://test:q1w2e3r4@192.168.0.110:8080/liferay-portlet/api/secure/jsonws/customuserauthentication/authenticate-by-user-name
表单编码值
companyId:10154
screenName:xyz
password:xyz
active:true
如果我在Postman中放置这个请求,它会正确地获取JSON响应。
现在当我从我的Android代码中调用相同的请求时,我会得到一个“未经授权”的响应。
我的Retrofit服务
public interface LoginApi {
@FormUrlEncoded
@POST("/liferay-portlet/api/secure/jsonws/customuserauthentication/authenticate-by-user-name")
Call<User> login(@Field("companyId")long companyId,@Field("screenName")String screenName,@Field("password")String password,@Field("active")boolean active);
}
我的RestApiManager类(此类用于调用服务接口并创建Retrofit Builder)
public class RestApiManager {
private LoginApi loginApi;
public LoginApi login() {
if (loginApi==null) {
GsonBuilder gson=new GsonBuilder();
gson.registerTypeAdapter(String.class, new StringDeserializer());
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://test:q1w2e3r4@192.168.0.110:8080")
.addConverterFactory(GsonConverterFactory.create())
.build();
loginApi=retrofit.create(LoginApi.class);
}
return loginApi;
}
调用RestApiManager
Call<User> callUser=restApiManager.login().login(loginData.getCompanyId(),loginData.getScreenName(),loginData.getPassword(),loginData.isActive());
callUser.enqueue(new Callback<User>() {
@Override
public void onResponse(Response<User> response, Retrofit retrofit) {
Log.d("Login","Login Response:"+response.body());
}
@Override
public void onFailure(Throwable t) {
Log.d("Login","Login Response:"+t.getMessage());
}
});