Most non-GET requests would have some content in the request body.
An example of information you want to include in the request body is the details of the new employee you are creating with your request.
In general, the request body is just a sequence of bytes. In the context of web services, it is usually a text that encodes certain details. The text can be a URL-encoded or JSON representation of a set of values.
As mentioned in the previous sections, the Content property of the HttpClientRequest/XPRIM_HttpRequest contains the following methods that you can use to add content to your request body in the required format:
| XPRIM_HttpRequest | HttpClientRequest |
AddFile | Yes | Yes |
AddJson | Yes | Yes |
AddJsonArray | Yes | Yes |
AddJsonObject | Yes | Yes |
AddString | Yes | Yes |
AddUrlEncodedFormValue | Yes | Yes |
AppendString | - | Yes |
Refer to the limitations of using AddFile on IBM i.
Example - Creating a new Employee using a Web API
Let's say your company has a published API for creating new employees.
The URL looks like this:
http://yourcompany.com/api/hr/employee
Let's have a look at how you can add the details to the request body. The first example shows how to add the details as URL-encoded form values, and the second example adds the content as a JSON string.
Adding the employee details as URL-encoded form values
Define_Com Class(#PRIM_SRVM.HttpClientRequest) Name(#Req)
#Req.Content.AddUrlEncodedFormValue Name('givenName') Value(#EmpGivenName)
#Req.Content.AddUrlEncodedFormValue Name('lastName') Value(#EmpLastName)
#Req.Content.AddUrlEncodedFormValue Name('address') Value(#EmpAddress)
* Execute the request (POST verb)
#Req.DoPost Url('http://yourcompany.com/api/hr/employee')Adding the employee details as JSON
Define_Com Class(#PRIM_SRVM.HttpClientRequest) Name(#Req)
Define_Com Class(#PRIM_JSON.Document) Name(#Json)
Define_Com Class(#PRIM_JSON.Object) Name(#JsonObject) Reference(*DYNAMIC)
* Construct the JSON object
#JsonObject <= #Json.CreateRootObject
#JsonObject.AddStringMember Name('givenName') Value(#EmpGivenName)
#JsonObject.AddStringMember Name('lastName') Value(#EmpLastName)
#JsonObject.AddStringMember Name('address') Value(#EmpAddress)
* Add the constructed JSON to the request body
#Req.Content.AddJson Value(#Json)* Execute the request (POST verb)
#Req.DoPost Url('http://yourcompany.com/api/hr/employee')