square / retrofit

A type-safe HTTP client for Android and the JVM
https://square.github.io/retrofit/
Apache License 2.0
43.12k stars 7.3k forks source link

retrofit2.OkHttpCall$ExceptionCatchingResponseBody #3666

Closed fajaranugrah closed 2 years ago

fajaranugrah commented 2 years ago

There problem on this

Request with void: @GET("/resource/{id}") void getResource(@path("id") int resId);

Error: err: java.lang.ClassCastException: retrofit2.OkHttpCall$ExceptionCatchingResponseBody cannot be cast to java.lang.Void

Response from the API: Retrofit﹕ <--- HTTP 200 ... Retrofit﹕ <--- END HTTP (0-byte body)

my version is

   // define a BOM and its version
    implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.3"))
    // define any required OkHttp artifacts without version
    implementation("com.squareup.okhttp3:okhttp")
    implementation("com.squareup.okhttp3:logging-interceptor")
    //Okio
    implementation 'com.squareup.okio:okio:2.10.0'
    // retrofit2
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

can you help me? thank you

otnieldocs commented 2 years ago

I don't think you can set the return value with void, as per what was written in this docs, you need to specify the return value as documented here https://square.github.io/retrofit/ Instead of void getResource(@path("id") int resId); I think you need to change the return type with Call<YourPOJO> getResource(@path("id") int resId);

JakeWharton commented 2 years ago

That's right, but Retrofit should have failed much earlier than this so there's still a problem.

JakeWharton commented 2 years ago

I cannot reproduce.

With:

final class VoidReturn {
  interface Example {
    @GET("stuff")
    void stuff();
  }

  public static void main(String... args) throws Exception {
    MockWebServer server = new MockWebServer();

    Retrofit retrofit =
      new Retrofit.Builder()
        .baseUrl(server.url("/"))
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    Example service = retrofit.create(Example.class);

    service.stuff();
  }
}

I get:

Exception in thread "main" java.lang.IllegalArgumentException: Service methods cannot return void.
    for method Example.stuff
    at retrofit2.Utils.methodError(Utils.java:56)
    at retrofit2.Utils.methodError(Utils.java:44)
    at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:36)
    at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:208)
    at retrofit2.Retrofit$1.invoke(Retrofit.java:166)
    at com.example.retrofit.$Proxy0.stuff(Unknown Source)
    at com.example.retrofit.VoidReturn.main(VoidReturn.java:24)