Android应用中Retrofit调用API无法获取帖子问题求助
开发Android社交应用时,使用Retrofit发起API请求获取帖子,请求成功但响应中未返回任何帖子。
API相关信息
API端点:https://api.example.com/api/v1/post/post
请求方法:GET
必填参数:page(整数)、size(整数)
请求头:Authorization(包含有效认证令牌)
已确认请求发起正确且请求头包含有效令牌,但响应中无帖子数据。
Android Studio日志
2023-07-07 16:21:23.737 I Auth Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJqb2huQGdtYWlsLmNvbSIsInJvbGVzIjpbIlVTRVIiXSwiaXNzIjoiL2FwaS92MS9sb2dpbiIsImV4cCI6MTY4ODc0MzI4Mn0.LaYnVqLrUtAG7weC0hk56W7anVt9nWmYet8Zg1lAuOg 2023-07-07 16:21:32.075 I we should get the posts here retrofit2.OkHttpCall$NoContentResponseBody@df0ef6d 2023-07-07 16:21:32.076 I number of posts: 0 2023-07-07 16:21:32.076 I total pages: 0 2023-07-07 16:21:32.076 I total elements: 3
日志显示返回帖子数为0,但实际存在3条帖子,且Postman请求该API能正常返回包含3条帖子的响应体。
Android端请求代码片段
// Make the API call to fetch the list of posts PostService postService = retrofit.create(PostService.class); Call<PostPage> call = postService.getAllPosts(authToken,10, 15); // Replace page and size with your desired values call.enqueue(new Callback<PostPage>() { @Override public void onResponse(Call<PostPage> call, Response<PostPage> response) { System.out.println("we should get the postts here " + response.raw().body().toString()); System.out.println("header check " + response.headers()); if (response.isSuccessful() && response.body()!=null) { PostPage postResponse = response.body(); List<Post> posts = postResponse.getPosts(); if (posts != null) { int totalPages = postResponse.getTotalPages(); long totalElements = postResponse.getTotalElements(); System.out.println("number of posts: " + posts.size()); System.out.println("total pages: " + totalPages); System.out.println("total elements: " + totalElements); postAdapter.setPostList(posts); } else { // Handle the case when the 'posts' list is null System.out.println("Received null posts list"); } } else { // Handle error // Handle the login error here System.out.println("Something went wrong displaying the post"); Toast.makeText(MainActivity.this, "Login Error", Toast.LENGTH_SHORT).show(); } } });
服务器端控制器代码片段
@GetMapping("/api/v1/post/post") public ResponseEntity<PostPage> getAllPost(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size, @RequestHeader("Authorization") String authorizationHeader) { // Extract email from the authorization header and retrieve the user // ... // Retrieve the posts using the page and size parameters Page<Post> post = postService.getAllPost(PageRequest.of(page, size)); List<Post> posts = post.get().toList(); // Create a PostPage object and set the necessary fields PostPage postPage = new PostPage(); postPage.setPosts(posts); postPage.setTotalPages(post.getTotalPages()); postPage.setTotalElements(post.getTotalElements()); postPage.setCurrentPage(post.getNumber()); return ResponseEntity.ok().body(postPage); }
排查建议
检查分页参数顺序与取值
你调用getAllPosts(authToken,10,15)时传入的page=10、size=15,但服务器端总共只有3条数据,按每页15条计算仅存在第0页数据,第10页自然无内容。将page参数改为0或1(取决于服务器分页索引规则),比如getAllPosts(authToken,0,15)再测试。同时确认PostService接口中page和size的参数顺序与服务器接收顺序一致。核对JSON字段映射
确保PostPage类的字段名与服务器返回的JSON字段完全匹配,若存在字段名不一致情况,需添加@SerializedName注解指定映射关系。另外,PostPage类必须提供无参构造函数,否则Gson无法正常解析响应体。示例:public class PostPage { @SerializedName("posts") // 若服务器返回字段名不同需修改 private List<Post> posts; private int totalPages; private long totalElements; private int currentPage; public PostPage() {} // 必须有无参构造函数 // Getter和Setter方法 public List<Post> getPosts() { return posts; } public void setPosts(List<Post> posts) { this.posts = posts; } // 其他Getter/Setter... }确认Retrofit转换器配置
检查Retrofit是否添加了Gson转换器工厂,否则无法解析JSON响应体:Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build();抓包验证请求详情
添加OkHttp日志拦截器查看完整请求与响应内容,确认发送的参数、请求头与Postman一致:HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(logging) .build(); // 在Retrofit构建中使用该client Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build();
内容的提问来源于stack exchange,提问作者ABAB

