【发布时间】:2017-10-10 04:50:59
【问题描述】:
来自服务器的响应如下:
{
success: true,
token: "someRandomToken"
}
如何从响应中检索token?
我尝试遵循here 提供的解决方案,但我无法在 onResponse method 内的Call 中添加泛型
编辑
这是我的方法
public void loginUser(final Context context, String url, String username, String passowrd, loginJson loginjson) {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
loginjson.setUsername(username);
loginjson.setPassword(passowrd);
Gson gson = new Gson();
String jsonFromForm = gson.toJson(loginjson);
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, jsonFromForm);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("content-type", "application/json; charset=utf-8")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println("Failure!!");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if(response.isSuccessful()) {
if (context != null) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if(response.body() != null){
}
}
});
}
//
} else {
if (context != null) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.failed_to_login),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
}
实施@Piyush Patel 回答后:
我将Call 和Response 分别更改为retrofit2.Call<tokenRetrieved> 和retrofit2.Reponse<tokenRetrieved>。但是我的enqueue 中的Callback 提示错误,要求我实现其onResponse 和onFailure 方法
新手问题:我在使用retrofit1 方法吗?!!
【问题讨论】:
-
首先你使用 okhttp 请求 API 你需要 import compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.okhttp3:okhttp:3.6.0'在 app.gradle 中编译 'com.squareup.retrofit2:converter-gson:2.1.0' 依赖项以使用改造
-
@PiyushPatel whopps!!,非常感谢,谢谢
-
这是我的荣幸..!如果您对改造有任何疑问,请在这里提问,我会回复您。
-
@PiyushPatel 好的,再次感谢 :)
-
使用 OkHttpClient 解析响应成功的数据确实为您工作 if(response.body() != null){ JsonResponse jsonResponse=gson.fromJson(response.body(), JsonResponse.class); }
标签: java android gson retrofit2