使用 Groovy 使用 Opentext Rest API

Consume Opentext Rest API using Groovy

我需要使用 Groovy 使用他们的 Rest API 在 opentext 中创建一个组:

所以我尝试使用这个代码

    @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()

不幸的是,它向我显示了这条错误消息:

响应代码 = 400

PS:当我尝试使用“Get/PUT/DELETE”方法时,这段代码就像变魔术一样有效!该问题仅出现在“POST”

实际上问题是:为了使用创建选项,您需要使用 MultipartEntityBuilder,这是对我有用的代码:

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);