Android 如何以自定义对象作为主体创建2.响应?
在Android应用程序中,我使用Refught2执行http请求。 很好 为了创建错误响应,我还使用以下方法:Android 如何以自定义对象作为主体创建2.响应?,android,retrofit2,okhttp,Android,Retrofit2,Okhttp,在Android应用程序中,我使用Refught2执行http请求。 很好 为了创建错误响应,我还使用以下方法: import okhttp3.MediaType import okhttp3.Protocol import okhttp3.Request import okhttp3.ResponseBody import retrofit2.Response private val CODE_TEMPLATE = "[CODE_TEMPLATE]" private val
import okhttp3.MediaType
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.ResponseBody
import retrofit2.Response
private val CODE_TEMPLATE = "[CODE_TEMPLATE]"
private val MESSAGE_TEMPLATE = "[MESSAGE_TEMPLATE]"
private val templateBody =
"{\n" + "\"code\": $CODE_TEMPLATE,\n" + "\"message\": \"$MESSAGE_TEMPLATE\"\n" + "}"
private fun createTransportErrorResponse(
code: Int = defaultCode,
message: String = defaultMessage
): Response<*> {
val body =
templateBody.replace(CODE_TEMPLATE, "$code").replace(MESSAGE_TEMPLATE, "$message")
val rawResponse = okhttp3.Response.Builder()
.code(code)
.message(message)
.protocol(Protocol.HTTP_1_1)
.request(Request.Builder().url(BuildConfig.API_BASE_URL).build())
.build()
val responseBody = ResponseBody.create(
MediaType.parse("application/json"),
body
)
val errorResponse = Response.error<Response<*>>(responseBody, rawResponse)
return errorResponse
}
}
我需要Response.body
成为我的自定义对象(Bonus
)
是的,你能做到。@RajasekaranM你有什么例子吗?Thanks@RajasekaranM我需要我的自定义对象作为响应。body不在请求中。body你的意思是
Response.success(Bonus())
?
class Bonus {
var id: Int = 0
var balance: Double = 0.0
var name: String = ""
}