The new REST api and the use of Param and Body

27 views
Skip to first unread message

rdvg...@gmail.com

unread,
Aug 17, 2019, 2:01:49 PM8/17/19
to CodenameOne Discussions
Hi,

I am trying to create a record in a Mysql BD. In the client I use the new API Rest but it sends me the following error when I include a Param method with Body:

"[EDT] 0: 0: 0.2 - Exception: java.lang.IllegalStateException - Request body and arguments are mutually exclusive, you can't use both"

On the server I use Spring Boot and I accept the 2 conditions (at least it doesn't send compilation error).
Any idea how to do it correctly?

My client code:
    public static Response addMarcacion(Marcacion m) {
        Response<String> r = Rest.post(SERVER_URL + "marcacion/adicionCambio").
                jsonContent().
                queryParam("token", UsuarioService.getToken()).
                body(m.getPropertyIndex().toJSON()).getAsString();
        return r;
    }

My server code;
    @RequestMapping(method = RequestMethod.POST,value = "/adicionCambio")
    public @ResponseBody String addMarcacion(
    @RequestParam(name="token", required = true) String token, 
    @RequestBody MarcacionDAO mDAO) throws IOException, ParseException {
        if(mDAO.getMarcacionID() != null) {
        marcaciones.updateMarcacion(token, mDAO);
            return mDAO.getMarcacionID().toString();
        } else {
            return marcaciones.addMarcacion(token, mDAO);
        }
    }

Shai Almog

unread,
Aug 18, 2019, 12:50:19 AM8/18/19
to CodenameOne Discussions
Hi,
queryParam adds an argument to the request. When it's a get request it's added to the URL e.g. url?token=val
When it's a port request these parameters are placed in the body of the post (that's HTTP's form post standard). This is obviously problematic for this case.

Some developers use the GET request semantic with POST but that goes against HTTP guidelines and some tools don't support that. You can hack it by changing the URL but the "right way" is to add the token as an HTTP header. This is the common convention and there are a few advantages to doing it this way.

First in the server side you just need to do:
@RequestHeader(name="token", required = true) String token

That's it... Then in the client side you can do something like:
header("token", UsuarioService.getToken())

But there's an even better way:
NetworkManager.getInstance().addDefaultHeader("token", UsuarioService.getToken());

This will work globally from this point onward.

rdvg...@gmail.com

unread,
Aug 18, 2019, 3:33:41 AM8/18/19
to CodenameOne Discussions
Hi,

Thanks for information.
Reply all
Reply to author
Forward
0 new messages