Retrofit响应体返回null问题排查求助
问题排查与解决方案
1. 修正BaseUrl的端口格式错误
你当前的BaseUrl写成了"http://10.0.2.2/8000/",错误地将端口号作为路径的一部分,正确的端口格式应该用冒号分隔:
private val retrofit = Retrofit.Builder() .baseUrl("http://10.0.2.2:8000/") // 将/8000改为:8000 .addConverterFactory(GsonConverterFactory.create()) .client(client) .build()
这个错误会导致Retrofit请求的实际URL与Postman测试的正确URL不符,服务器返回的内容并非预期JSON结构,最终Gson解析失败返回null。
2. 对齐请求体的字段类型
你在Postman中提交的IsBanned是整数1,但代码里传入的是布尔值false,Gson会将布尔值序列化为"IsBanned": false,而服务器可能只接收整数类型的0/1,这会导致服务器无法正确处理请求,返回异常响应。
解决方法:
- 修改数据类中
IsBanned的类型为Int?:
data class UserLogin( @SerializedName("Email") val Email: String, @SerializedName("UserId") val UserId: Int?, @SerializedName("IsBanned") val IsBanned: Int?, // 改为Int?类型 @SerializedName("firebaseUid") val firebaseUid: String? )
- 调用时传入整数
0或1:
val userInfo = UserLogin(UserId = null,firebaseUid = "TestTestTest", IsBanned = 0, Email = "test@gmail.com");
3. 打印完整响应内容定位解析问题
在onResponse方法中添加日志代码,打印响应状态码、原始响应体及错误信息,明确服务器返回的实际内容:
override fun onResponse(call: Call<UserLogin>, response: Response<UserLogin>) { Log.d("Retrofit Code", response.code().toString()) // 打印解析后的响应体JSON response.body()?.let { Log.d("Retrofit Response", Gson().toJson(it)) } // 打印错误响应体(若请求未成功) if (!response.isSuccessful) { response.errorBody()?.string()?.let { Log.d("Retrofit Error", it) } } val addedUser = response.body() onResult(addedUser) }
同时给OkHttp添加日志拦截器,查看完整的请求和响应细节:
// 先添加依赖:implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0' private val client = OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build()
通过日志可以直接对比Postman和Retrofit的请求体、响应体是否一致。
4. 确认RestApi接口定义正确性
确保你的RestApi接口中addUser方法正确添加了@POST和@Body注解:
interface RestApi { @POST("users/") fun addUser(@Body userData: UserLogin): Call<UserLogin> }
如果缺少@Body注解,Retrofit不会将userData序列化为请求体发送,服务器无法获取参数,会返回不符合预期的响应。
内容的提问来源于stack exchange,提问作者Siqueler
相关产品推荐
相关产品推荐

