Retrofit post a object parameter, but receive a "parameter is not present" error

491 Views Asked by At

Here is my spring boot controller:

@RestController
@RequestMapping("/api/v1/geo-media/")
class GeoMediaController {
@PostMapping("create")
    fun saveMedias(@RequestHeader("token") token: String,
                   @RequestParam mediaGroup: WalkMediaGroup):Result<String> {
    }
}

Here is the parameter class:

class WalkMediaGroup (
    val wid: Long,
    val mediaGroup: MediaGroup
)

class MediaGroup(
    val node: Node,
    val medias: List<Media>
)

class Media (
    val type: Int,
    val content: String,
    val remark: String
)

Then my Retrofit service class:

interface ApiService {
    @Headers("Content-Type: application/json")
    @POST("geo-media/create")
    fun createGeoMedias(
        @Body mediaGroup: WalkMediaGroup
    ): Call<Result<String>>
}

Above is the key parts of my code. I don't know why that I received error.

{
    "timestamp":"2019-10-25T11:46:10.247+0000",
    "status":400,
    "error":"Bad Request",
    "message":"Required WalkMediaGroup parameter 'mediaGroup' is not present",
 ......
}
1

There are 1 best solutions below

0
Shashanth On BEST ANSWER

From Android (or whatever the client it maybe) you're posting JSON body. In order to receive that JSON body parameter in server you've to use Spring Boot @RequestBody() annotation instead of @RequestParam() annotation.

So, in your Spring Boot API code just change the annotation from @RequestParam() to @RequestBody(). That's it!

@PostMapping("create")
fun saveMedias(
    @RequestHeader("token") token: String,
   /* notice the change here ==> */ @RequestBody mediaGroup: WalkMediaGroup):Result<String> {
}