Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

389
Visualizações
How to create dummy ResponseBody object which required by OkHttp? [Solved]

I'm passing null right now, which causes a crash!

See: val response: Response<ReviewResponse> = Response.error(-1, null)

Code:

suspend fun getReviewData() = getResult {
        try {
            apiService.getReviewData(getCustomerId())
        } catch (e: Exception) {
            val response: Response<ReviewResponse> = Response.error(-1, null)
            response
        }
    }

   

As you can see null is not accepting internally, and I must need pass this: ResponseBody body

enter image description here

over 4 years ago · Santiago Trujillo
5 Respostas
Responde à pergunta

0

Depend on your requirement addBody() function you are not passing any param here. need to pass param.

look like api construction in your code missing . please follow link to know more- https://www.chillcoding.com/android-retrofit-send-http/

++ update depend on your comment i think you not get direct answer , i am not give direct answer, its depend on exact architecture you following. little bit more info java.lang.IllegalArgumentException: code < 400: -1 its define architecture.

 if (code < 400) throw new IllegalArgumentException("code < 400: " + code);

here i suggest you how you going to return result its quite complicated , you try with some custom class with error handle and success handle.

data class ResponseByApi(val success: Any, val code: Int, val 
error : Any)

create response model class and set value as per network response like success set success body and code else if fail set error body and code -> return as per response.

over 4 years ago · Santiago Trujillo Relatório

0

See this:

suspend fun getReviewData() = getResult {..}

Looks like your getResult return type is OkHttp non nullable response. Make your function as nullable, so that you can pass null here, and in UI handle the null check.

PS: Why I'm suggesting it, because anyhow you're sending dummy response which has no usage and you're doing because you must need to return to solve compiler error, isn't it?

Simple!

UPDATE:

private fun getDummyResponseBody(): ResponseBody {
        val jsonObject = JSONObject()
        return jsonObject.toString().toResponseBody()
    }

Hope it works!

over 4 years ago · Santiago Trujillo Relatório

0

You can create a result data class like this

 data class ApiResult<out T>(
    val status: Status,
    val data: T?,
    val error: Throwable?,
    val message: String?
) {

    enum class Status {
        SUCCESS,
        ERROR,
        LOADING
    }

    companion object {
        fun <T> success(data: T?): ApiResult<T> {
            return ApiResult(Status.SUCCESS, data, null, null)
        }

        fun <T> error(message: String, error: Throwable?): ApiResult<T> {
            return ApiResult(Status.ERROR, null, error, message)
        }

        fun <T> loading(data: T? = null): ApiResult<T> {
            return ApiResult(Status.LOADING, data, null, null)
        }
    }

    override fun toString(): String {
        return "Result(status=$status, data=$data, error=$error, message=$message)"
    }
}

and then create your custom base response like this

 data class CommonResponse<T>(
    @SerializedName("error") val error: Boolean,
    @SerializedName("status") val status: Int,
    @SerializedName("message") val message: String?,
    @SerializedName("response") val response: T?
)

and assign them like this in retrofit

suspend fun <T> getResponse(
        request: suspend () -> Response<T>
    ): ApiResult<T> {
        return try {
            val result = request.invoke()
            if (result.isSuccessful) {
                return ApiResult.success(result.body())
            } else {

                ApiResult.error("Error", null)
            }
        } catch (e: Throwable) {
            ApiResult.error("Unkown Error", e)
        }
    }

and use them like this in call

interface CheckWhereApi {
    //Check Where API
    @GET("url")
    suspend fun checkWhere(): Response<CommonResponse<MyModel>>
}
over 4 years ago · Santiago Trujillo Relatório

0

What about this:

Response.error(404, ResponseBody.create(null, "Not found response body"))
over 4 years ago · Santiago Trujillo Relatório

0

I see that the code looks:

public static <T> Response<T> error(int code, ResponseBody body) {
    Objects.requireNonNull(body, "body == null");
    if (code < 400) throw new IllegalArgumentException("code < 400: " + code);
    return ... // build error response
}

And you call it:

val response: Response = Response.error(-1, null)

Thus, it will fail by NullPointerException.

Even if you comment on this line, it will fail by IllegalArgumentException because the code is less than 400.

However, you need to return Response<ReviewResponse> type.

You could use ResponseEntity for this:

new ResponseEntity<>(HttpStatus.OK);

It will be exactly creating dummy ResponseBody object which required by OkHttp. But you need to use ResponseEntity instead of Response.

Or you could throw exception, like:

throw new ResponseStatusException(
    HttpStatus.NOT_FOUND, "entity not found"
);

From org.springframework.web.server.ResponseStatusException

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda