我现在已经尝试了一天半的Retrofit,但Retrofit似乎不喜欢我的编程方法。
我的状态代码:200 并且没有错误,但正文总是空的。我尝试了不同的API,因此我确信这是我的短代码中的一些架构故障。
注意:在这里和那里使用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'
}
要明确:
问题:身体总是空的。
以下是我的代码的副本,我感谢任何建议。
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();
答案 0 :(得分:4)
我认为问题可以在这里:
.addConverter(String.class, new ToStringConverter())
尝试转换为GitResult类或尝试这样:
Retrofit client = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
答案 1 :(得分:1)
我有同样的问题,问题是GSON的JSON映射有问题。服务器发送的JSON对象密钥和我使用的不匹配。
如果响应代码是HTTP_OK但响应正文错误,则表示解析响应时出现问题。仔细检查响应中的JSON键/属性是否与模型中的键映射匹配。
答案 2 :(得分:1)
我尝试连接到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
课程与Response
的{{1}}不符。我建议您更改Server
课程,如下所示
GitResult
希望有所帮助!