I need to create a group in opentext using their Rest API using Groovy:
So I tried to use this code
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.5.2')
import groovy.json.*
import org.apache.http.client.methods.*
import org.apache.http.entity.*
import org.apache.http.impl.client.*
// build JSON
def map = [:]
map["type"] = 1
map["name"] = "ThisIsAGroup"
def jsonBody = new JsonBuilder(map).toString()
// build HTTP POST
String auth = "login:Password";
String encoding = auth.bytes.encodeBase64().toString()
def url = 'https://link_of_my_server/api/v2/members'
def post = new HttpPost(url)
post.setHeader("Authorization", "Basic " + encoding);
post.addHeader("content-type", "application/json")
post.setEntity(new StringEntity(jsonBody))
// execute
def client = HttpClientBuilder.create().build()
def response = client.execute(post)
def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
def jsonResponse = bufferedReader.getText()
unfortunately, it shows me this error message :
with Response Code = 400
PS: When I try to consume a "Get/ PUT/ DELETE" method , this piece of code works like magic ! the problem appears only with the "POST"
Actually the problem is : in order to use the creation option you need to use MultipartEntityBuilder
and here it is the code that worked for me :
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
CloseableHttpClient client = HttpClients.createDefault();
HttpResponse response = null;
HttpPost request = new HttpPost("http://path_to_my_server/otcs/cs/api/v1/members");
String auth = "login:password";
String encoding = auth.bytes.encodeBase64().toString()
request.setHeader("Authorization", "Basic " + encoding);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("type", new StringBody("1",ContentType.MULTIPART_FORM_DATA));
builder.addPart("name", new StringBody("groupName",ContentType.MULTIPART_FORM_DATA));
HttpEntity entity = builder.build();
request.setEntity(entity);
response = client.execute(request);