我开始使用 Retrofit,但我坚持这个简单的步骤。我有一个登录表单,我正在尝试通过服务器进行身份验证,但我无法发送请求。
这是我尝试过的:
我的改造客户:
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
我的登录界面:
public interface Login {
@POST(LOGIN)
Call<String> loginWithCredentials(@Body LoginCredentials data);
}
LoginCredentials 类:
public class LoginCredentials {
private String name;
private String pass;
public LoginCredentials(String name, String pass) {
this.name = name;
this.pass = pass;
}
}
我称之为的部分:
@Override
public void onClick(View v) {
showProgress(true);
String username = userField.getText().toString();
String password = passField.getText().toString();
ApiController.Login loginClient = ApiController.createService(ApiController.Login.class);
Call<String> call =loginClient.loginWithCredentials(new LoginCredentials(username, password));
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
handleResponse(response.body());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
showProgress(false);
Log.e(TAG, t.getLocalizedMessage());
}
});
}
我不断收到错误Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
但我不知道这意味着什么。
我想到了。这比我想象的要容易。您可以跳过解析Retrofit
通过将方法的响应类型设置为ResponseBody
。您只需要阅读响应并使用string()
提供的方法。就是这样!
Example:
public interface Login {
@POST(LOGIN)
Call<ResponseBody> loginWithCredentials(@Body LoginCredentials data);
}
然后像这样使用:
String username = userField.getText().toString();
String password = passField.getText().toString();
ApiController.Login loginClient = ApiController.createService(ApiController.Login.class);
Call<ResponseBody> call = loginClient.loginWithCredentials(new LoginCredentials(username, password));
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
// get String from response
String stringResponse = response.body().string();
// Do whatever you want with the String
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// handle error
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)