我的 grails 2.2.4 应用程序需要支持通过 HTTP 从第三方应用程序接受文件并发送文件,在对其进行一些调整后,作为对第三方应用程序的响应返回。
我想使用InputStream
将第三方应用程序发送的数据转换为文件,然后使用OutputStream
将文件发送回
所以我构建了这段代码:
API 类
class ApiResponse {
ApiMeta meta
ApiObject apiObj
}
class ApiMeta {
int code
String errorType
List msgs = []
}
class ApiObject {
OutputStream os
}
//对象编码器
JSON.registerObjectMarshaller( ApiObject ) { ApiObject obj ->
//How can I send output stream as json?
}
Controller
//controller
def save() {
request.withFormat {
json {
ApiResponse resp
//How can I convert the JSON data in params to a file?
response.status = 201
resp = new ApiResponse(
meta: new ApiMeta(code: 201),
apiObj: new ApiObject(os: transfers))
render resp as JSON
}
multipartForm {
}
}
问题
- 如何将第三方服务发送的 JSON 负载转换为文件?
- 是否可以将
OutputStream
放入我的ApiObject
类中,以便我可以将 JSON 负载发送回服务?
最佳答案
My grails 2.2.4 app needs to support accepting InputStream over HTTP from a third party application and sending OutputStream as a response back.
这确实没有意义。第三方应用无法真正向您的应用发送 InputStream
,而您的应用也无法真正发回 OutputStream
。第三方应用程序可以向您发送请求正文中的数据,您可以通过从请求中检索 InputStream
来读取正文,当您将数据放入响应中时也可能会发生同样的情况。第一次阅读时,我以为您可能只是以一种没有意义的方式措辞,但是当我看到您的域类时,这表明您可能真的对其工作原理感到困惑。
class Request {
InputStream instream
OutputStream outstream
static constraints = {
instream nullable: false, blank: false
}
}
你不能这么做。您无法将 InputStream
或 OutputStream
持久保存到数据库。
编辑:
如果您有这样的 Controller :
class MyController {
def someAction(Widget w) {
// do whatever you need to do with the Widget
}
}
class Widget {
String name
String category
}
然后您向该 Controller 操作发送一个带有 JSON 正文的请求,如下所示...
{"name":"Robert","category":"Prog Rocker"}
Grails会自动读取请求正文并进行相应的绑定(bind)。您永远不必直接与任何输入流交互才能实现这一点。这是您正在寻找的东西吗?
关于java - 如何创建接受InputStream作为参数的API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24476719/