【问题标题】:Consume Opentext Rest API using Groovy使用 Groovy 使用 Opentext Rest API
【发布时间】:2021-04-08 16:35:56
【问题描述】:

我需要使用他们的 Rest API 使用 Groovy 在 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”

【问题讨论】:

    标签: rest groovy opentext


    【解决方案1】:

    实际上问题是:为了使用创建选项,您需要使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多