groovy中多部分/表单数据的编码器功能 [英] encoder function for multipart/form-data in groovy

查看:111
本文介绍了groovy中多部分/表单数据的编码器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用jpeg图像和JSON文件作为内容来形成一个'multipart/form-data'REST请求.我坚持将'multipart/form-data'编码为zip文件.

I need to form a 'multipart/form-data' REST request with jpeg image and JSON file as the content.I am stuck with encoding the 'multipart/form-data' as a zip file.

有人可以告诉我,如何使用时髦的RESTClient做到这一点吗?我找不到与此有关的任何文档.

Can someone tell me, how I can achieve this with groovy RESTClient? I could not find any documentation regarding this.

推荐答案

As it can be seen in the docs RESTClient extends HTTPBuilder. HTTPBuilder has a getEncoder method that can be used to add dedicated encoder (with type and method). See the following piece of code:

import org.codehaus.groovy.runtime.MethodClosure
import javax.ws.rs.core.MediaType

//this part adds a special encoder    
def client = new RESTClient('some host')
client.encoder.putAt(MediaType.MULTIPART_FORM_DATA, new MethodClosure(this, 'encodeMultiPart'))

//here is the method for the encoder added above
HttpEntity encodeMultiPart(MultipartBody body) {
    MultipartEntityBuilder.create()
    .addBinaryBody(
        'file', 
        body.file, 
        ContentType.MULTIPART_FORM_DATA, 
        body.filename
    ).build()
}

//here's how MultipartBody class looks:
class MultipartBody {
   InputStream file
   String filename
}

现在要创建多部分请求,您需要将 MultipartBody 的实例作为请求的主体参数传递.

Now to create a multipart request You need to pass an instance of MultipartBody as a body argument to the request.

这篇关于groovy中多部分/表单数据的编码器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆