简体   繁体   中英

HTTP GET with request body RETROFIT

I am using Retrofit to make api calls in my android application. I have to submit a @Body of JSON

@GET("api/")
void getData(@Body UserPostRequestBody request)

I get error message

retrofit.RetrofitError: apiCall: Non-body HTTP method cannot contain @Body or @TypedOutput.

Have you any idea?

To send data along with your Get Request you can do the following:

//sending data as a url parameter
@GET("/group/{id}/users")
List<User> groupList(@Path("id") int groupId);

as said in this SO answer , Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request- Roy Fielding.

The definition of GET as explained here in this answer explains that a body isn't supposed to mean anything, so Retrofit doesn't allow you to add a body. That said, it is not true that a server HAS to follow this format. It's entirely possible for a server to have a GET endpoint that not only takes, but REQUIRES a body. It would be "bad" architecture, but it seems a bit silly for Retrofit to limit what the library can do unnecessarily.

Furthermore, the various HTTP methods have different definitions for what they are SUPPOSED to do. For example a GET gets information, a POST creates a new entry/object by providing information to the server, a PUT updates an existing entry/object etc. The problem is, the easiest way to pass complex data to the server, especially when using retrofit, is by using JSON. So the ideal way to GET information from the server while providing a complex filter would be to send a JSON body along with the GET request. Unfortunately, there is no HTTP request method that allows for this under the spec.

当 API 需要 @POST 并且您正在使用 @GET 时也会发生此错误

If the request body you need to send is not to complex you can also specify the query parameters as https://myserverdomain.com?somebody[property1]=value specifically on retrofit you define it like this:

Observable<Response<SomeClass>> someMethod(@Query("somebody[property1]") int property1);

That will work at least if you are requesting to a rails server hope this answer helps somebody

  • GET call doesnt accept body use Query("key") or Path("key")

  • only POST method accepts Body @POST("api/") void getData(@Body UserPostRequestBody request)

To Send body in a GET request use:

@HTTP(method = "GET", path = "api/users", hasBody = true)
Observable<JobDeleteResponseModel> jobDelete(@Body UserPostRequestBody body);

as is described in this post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM