How to make a post json request to a rest api

18 views
Skip to first unread message

max

unread,
Jan 17, 2019, 8:16:04 PM1/17/19
to CodenameOne Discussions
Hello, I am programming on codename one using IntelJ IDEA CE 2017.2.6.
I am trying to make a request to a rest api - the cloud natural language api. I figured out how to make a request in the command line: 








curl -X POST https://language.googleapis.com/v1/documents:analyzeSyntax?key=[API KEY] -H "Content-Type: application/json" -d '{


"document":{ "type":"PLAIN_TEXT",


"content":"bob walks to the park"


},


"encodingType":"UTF8"


}'

But I do not know how to make the request in codename one. I read an article here https://www.codenameone.com/blog/new-rest-calls.html but I do not really understand where to put the lines of code talked about in the article. Right now my code looks like this but It is wrong
ConnectionRequest req2=new ConnectionRequest();
    req2
.setUrl("https://language.googleapis.com/v1/documents:analyzeSyntax?key=[API KEY]");
    req2
.setPost(false);
    req2
.setHttpMethod("POST");
   
String JsonData = "{document:{ type:PLAIN_TEXT, content:bob walks to the park },encodingType:UTF8}";
    req2
.addArgument("Content-Type: application/json",JsonData.toString());
   
NetworkManager.getInstance().addToQueueAndWait(req2);
   
JSONParser parser = new JSONParser();

   
Map<String,Object> result = null;
   
try {
*******        result = Rest.post("https://language.googleapis.com/v1/documents:analyzeSyntax?key=[API KEY]").jsonContent().body(JsonData).getAsJsonMap();
   
} catch (IOException e) {
        e
.printStackTrace();
       
System.out.println("fail");
   
}
I implement the code that I found on this website on the starred line but I think that I put it in the wrong place because I am getting an error. Could someone please show me how to correctly make a post json request to a rest api?
Thank you

Shai Almog

unread,
Jan 17, 2019, 10:43:24 PM1/17/19
to CodenameOne Discussions
I would suggest using the newer REST API https://www.codenameone.com/blog/rest-api-error-handling.html

E.g.:

Rest.
    post
("https://language.googleapis.com/v1/documents:analyzeSyntax?apiKey").
    jsonContent
().
    body
("place the JSON string of the request here").

    fetchAsJsonMap
(e -> {
       
Map<String, Object> m = e.getResultData();
       
// process response here...
   
});


maxlax...@gmail.com

unread,
Jan 18, 2019, 12:46:49 PM1/18/19
to CodenameOne Discussions
Thank you. This worked
Reply all
Reply to author
Forward
0 new messages