1
votes

I tested with Postman that my Spring Boot RESTfull API works correctly if I send a PUT request to http://localhost:8080/app with the header Content-Type = application/json and the body {"appName": "Fake app (for testing)"}. The response from this call is a simple random string and the status is "200 OK". I tried to replicate the same request with Codename One without success, I get a Dialog error with the text 400: null. What's wrong in the following code?

public static void registerApp() {
        ConnectionRequest request = new ConnectionRequest();
        request.setContentType("application/json");
        request.setUrl("http://localhost:8080/app");
        request.setHttpMethod("PUT");

        String appName = Display.getInstance().getProperty("AppName", "");

        request.addArgument("appName", appName);

        request.addResponseListener((e) -> {
            Log.p("App registered");
        });

        // request will be handled asynchronously
        NetworkManager.getInstance().addToQueue(request);
}

I also need to do some operations on the random string returned by the server (on success), but I don't know how to get that string.

enter image description here

1

1 Answers

1
votes

addArgument uses standard HTTP arguments used in form submission not JSON arguments so what you are getting (which you can see in the network monitor tool) is appName=appName within the body.

You could use:

request.setRequestBody("{\"appName\": \"Fake app (for testing)\"}");

Or more simply:

request.setRequestBody("{'appName': 'Fake app (for testing)'}");

Personally, I've been gravitating towards the newer Rest API which you can use like this:

Response<String> result = 
    Rest.put(url).
    jsonContent().
    body("{'appName': 'Fake app (for testing)'}").getAsString();

See https://www.codenameone.com/blog/terse-rest-api.html