Я пытаюсь обновить сейчас полтора дня, но, как мне кажется, Retrofit не любит мои методы программирования.Дооснащение - Продолжайте получать пустое тело от API
Я получаю Код состояния: 200 и никаких ошибок, но тело всегда пуст. Я пробовал разные API, поэтому я уверен, что это небольшой отказ архитектуры в моем коротком коде.
Примечание: Использование gitResult здесь и там, почему? Раньше я использовал API Githubs.
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'
}
Чтобы было ясно:
Проблема: тело всегда пусто.
Ниже приведена копия моего кода, я ценю любые предложения.
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();