You can use the REST API in an application written in Java
using Oracle JDeveloper as your development environment. Let's look at an example for
creating a Contact object using Java.
Note:
Do not use the code shown in this example in a production
environment.
To create a Contact object using Java:
-
Create a java file.
-
Import the classes you need in the java file. For
example:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
-
Open Properties and go to the Libraries and Classpath
section to see the jar files needed to access these classes. For example:
- Commons-logging-1.2.jar
- Httpclient-4.5.2.zip
- Httpcore-4.4.4.jar
- Commons-codec-1.9.jar
-
Start the main method of your application program by
instantiating a client that can make HTTP calls. For example:
HttpClient httpClient = HttpClientBuilder.create().build();
-
Create an HttpPost request to create a new item on the
server. For example:
HttpPost request = new HttpPost("https://Admin1:Admin1234@nancy-165.qb.lan/services/rest/connect/latest/contacts");
Note:
The request does not contain the ID for the Contact
object because it will be created on the server and returned in the
response.
-
Create a StringEntity object that holds the JSON data
for the new contact object. For example:
StringEntity params = new StringEntity ("{\"name\":{\"first\":\"Carol\",\"last\":\"Master\"},\"emails\":[{\"address\":\"ck@theoffice.com\",\"addressType\":{\"id\":0, \"invalid\":false]}]");
It is recommended that you use the StringEntity object
for sending the body of a REST HTTP request.
Note:
The Oracle B2C Service REST API documentation
describes the minimum fields that are required on a given operation for a
given object and how to create the JSON.
-
Add a request header to indicate the content type and
set the StringEntity 'params' as the request body. For example:
request.addHeader("content-type","text/plain");
request.setEntity(params);
-
Execute the request and extract the response body, which
holds the ID of the newly-created object. Convert the extracted response body to
string and display it on the screen. For example:
HttpResponse response = httpClient.execute(request)
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
System.out.println(content);
-
Save and close the java file.
-
Go to the Agent Desktop to verify that the new object
does not exist.
-
Run your Java application and view the output, which
includes the returned ID of the contact you just created. For example:
"id":14,
"lookupName": "Carol Master",
-
Refresh your Agent Desktop, locate and open the newly
created record, and verify that the Contact ID for the record is same as the ID
shown in the Java application.