Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2.0 method without response

In my current android project I'm sending some data to my web server with the new Retrofit 2.0 library. I only want to run a script there and the server does not return anything. I thought I can do this with this method:

@POST("persons/insert.php")
Call<Void> insert(@Field("Name") String name);

My problem now is, that Retrofit jumps to the onFailure method although the server returns 200. That happens because nothing can be converted to Void. So how should I fix this method? I want that the onResponse method is called if the server sends 200 back and the onFailure if an error occurred. How can I achieve that?

like image 942
Cilenco Avatar asked Oct 01 '15 13:10

Cilenco


People also ask

How do you handle an empty response in retrofit?

You can just return a ResponseBody , which will bypass parsing the response. Even better: Use Void which not only has better semantics but is (slightly) more efficient in the empty case and vastly more efficient in a non-empty case (when you just don't care about body).


2 Answers

You can have it return a ResponseBody.

@POST("persons/insert.php")
Call<ResponseBody> insert(@Field("Name") String name);

You will still get onResponse and onFailure, but it will not try to deserialize the stream to an object.

like image 102
iagreen Avatar answered Oct 05 '22 22:10

iagreen


You can completely avoid the response body. In beta2, you can do Call<Void> to discard the response body and just obtain the http status code.

@POST("persons/insert.php")
Call<Void> insert(@Field("Name") String name);
like image 7
Nikola Despotoski Avatar answered Oct 05 '22 23:10

Nikola Despotoski