首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Groovy使用Opentext Rest API

使用Groovy使用Opentext Rest API
EN

Stack Overflow用户
提问于 2021-04-09 00:35:57
回答 1查看 77关注 0票数 1

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

所以我试着使用下面的代码

代码语言:javascript
复制
    @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“中

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-09 17:24:49

实际上,问题是:为了使用创建选项,您需要使用MultipartEntityBuilder,下面是为我工作的代码:

代码语言:javascript
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67008280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档