改造 - 不断从 API 获得空体
Retrofit - Keep getting empty body from API
我已经尝试 Retrofit 一天半了,但 Retrofit 似乎不喜欢我的编程方法。
我收到 状态代码:200,没有错误,但正文始终为空。我尝试了不同的 APIs,所以我确定这是我的短代码中的一些架构错误。
注意: 到处使用 gitResult,为什么?我之前使用的是 Githubs API。
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
}
要明确:
Problem: body is always empty.
下面是我的代码的副本,我很感激任何建议。
public class MainActivity extends AppCompatActivity {
private UserAdapter adapter ;
List<Item> Users ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.listView);
Users = new ArrayList<Item>();
final ProgressDialog dialog = ProgressDialog.show(this, "", "loading...");
RestClient.GitApiInterface service = RestClient.getClient();
Call<GitResult> call = service.getUsersNamedTom();
call.enqueue(new Callback<GitResult>() {
@Override
public void onResponse(Response<GitResult> response) {
dialog.dismiss();
Log.d("MainActivity", "Status Code = " + response.code());
if (response.isSuccess()) {
// request successful (status code 200, 201)
GitResult result = response.body();
Log.d("MainActivity", "response = " + new Gson().toJson(result));
//Users = result.getItems();
Log.d("MainActivity", "Items = " + Users.size());
adapter = new UserAdapter(MainActivity.this, Users);
listView.setAdapter(adapter);
} else {
// response received but request not successful (like 400,401,403 etc)
//Handle errors
}
}
@Override
public void onFailure(Throwable t) {
dialog.dismiss();
}
});
..
public class GitResult {
private int totalCount;
private boolean incompleteResults;
private List<Item> items = new ArrayList<Item>();
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public boolean isIncompleteResults() {
return incompleteResults;
}
public void setIncompleteResults(boolean incompleteResults) {
this.incompleteResults = incompleteResults;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
public final class ToStringConverter implements Converter<String> {
@Override
public String fromBody(ResponseBody body) throws IOException {
return body.string();
}
@Override
public RequestBody toBody(String value) {
return RequestBody.create(MediaType.parse("text/plain"), value);
}
}
..
public class RestClient {
private static GitApiInterface gitApiInterface ;
private static String baseUrl = "http://jsonplaceholder.typicode.com" ;
public static GitApiInterface getClient() {
if (gitApiInterface == null) {
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverter(String.class, new ToStringConverter())
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
gitApiInterface = client.create(GitApiInterface.class);
}
return gitApiInterface ;
}
public interface GitApiInterface {
@GET("/posts/1")
Call<GitResult> getUsersNamedTom();
我遇到了同样的问题,问题是 JSON GSON 的映射有问题。 JSON 服务器发送的对象密钥与我使用的不匹配。
如果response Code是HTTP_OK但是response body是错误的,说明response解析有问题。仔细检查响应中的 JSON key/properties 是否与模型中的键映射匹配。
我尝试连接到 http://jsonplaceholder.typicode.com/posts/1
并得到响应:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
所以我认为您的 GitResult
class 与 Server
的 Response
不匹配。我建议您将 GitResult
class 更改为如下
public class GitResult {
public int getUserId() {
return this.userId
}
public int setUserId(int userId) {
this.userId = userId
}
int userId;
public int getId() {
return this.id
}
public int setId(int id) {
this.id = id
}
int id;
public String getTitle() {
return this.title
}
public String setTitle(String title) {
this.title = title
}
String title;
public String getBody() {
return this.body
}
public String setBody(String body) {
this.body = body
}
String body;
}
希望对您有所帮助!
我觉得问题可能出在这里:
.addConverter(String.class, new ToStringConverter())
尝试转换为 GitResult class 或这样尝试:
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
我已经尝试 Retrofit 一天半了,但 Retrofit 似乎不喜欢我的编程方法。
我收到 状态代码:200,没有错误,但正文始终为空。我尝试了不同的 APIs,所以我确定这是我的短代码中的一些架构错误。
注意: 到处使用 gitResult,为什么?我之前使用的是 Githubs API。
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.1' compile 'com.squareup.retrofit:retrofit:2.0.0-beta1' compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
}
要明确:
Problem: body is always empty.
下面是我的代码的副本,我很感激任何建议。
public class MainActivity extends AppCompatActivity {
private UserAdapter adapter ;
List<Item> Users ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.listView);
Users = new ArrayList<Item>();
final ProgressDialog dialog = ProgressDialog.show(this, "", "loading...");
RestClient.GitApiInterface service = RestClient.getClient();
Call<GitResult> call = service.getUsersNamedTom();
call.enqueue(new Callback<GitResult>() {
@Override
public void onResponse(Response<GitResult> response) {
dialog.dismiss();
Log.d("MainActivity", "Status Code = " + response.code());
if (response.isSuccess()) {
// request successful (status code 200, 201)
GitResult result = response.body();
Log.d("MainActivity", "response = " + new Gson().toJson(result));
//Users = result.getItems();
Log.d("MainActivity", "Items = " + Users.size());
adapter = new UserAdapter(MainActivity.this, Users);
listView.setAdapter(adapter);
} else {
// response received but request not successful (like 400,401,403 etc)
//Handle errors
}
}
@Override
public void onFailure(Throwable t) {
dialog.dismiss();
}
});
..
public class GitResult {
private int totalCount;
private boolean incompleteResults;
private List<Item> items = new ArrayList<Item>();
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public boolean isIncompleteResults() {
return incompleteResults;
}
public void setIncompleteResults(boolean incompleteResults) {
this.incompleteResults = incompleteResults;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
public final class ToStringConverter implements Converter<String> {
@Override
public String fromBody(ResponseBody body) throws IOException {
return body.string();
}
@Override
public RequestBody toBody(String value) {
return RequestBody.create(MediaType.parse("text/plain"), value);
}
}
..
public class RestClient {
private static GitApiInterface gitApiInterface ;
private static String baseUrl = "http://jsonplaceholder.typicode.com" ;
public static GitApiInterface getClient() {
if (gitApiInterface == null) {
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverter(String.class, new ToStringConverter())
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
gitApiInterface = client.create(GitApiInterface.class);
}
return gitApiInterface ;
}
public interface GitApiInterface {
@GET("/posts/1")
Call<GitResult> getUsersNamedTom();
我遇到了同样的问题,问题是 JSON GSON 的映射有问题。 JSON 服务器发送的对象密钥与我使用的不匹配。
如果response Code是HTTP_OK但是response body是错误的,说明response解析有问题。仔细检查响应中的 JSON key/properties 是否与模型中的键映射匹配。
我尝试连接到 http://jsonplaceholder.typicode.com/posts/1
并得到响应:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
所以我认为您的 GitResult
class 与 Server
的 Response
不匹配。我建议您将 GitResult
class 更改为如下
public class GitResult {
public int getUserId() {
return this.userId
}
public int setUserId(int userId) {
this.userId = userId
}
int userId;
public int getId() {
return this.id
}
public int setId(int id) {
this.id = id
}
int id;
public String getTitle() {
return this.title
}
public String setTitle(String title) {
this.title = title
}
String title;
public String getBody() {
return this.body
}
public String setBody(String body) {
this.body = body
}
String body;
}
希望对您有所帮助!
我觉得问题可能出在这里:
.addConverter(String.class, new ToStringConverter())
尝试转换为 GitResult class 或这样尝试:
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();