我看到用于保存独立附件的API。反向操作在哪里?
事实上,我注意到Cloudant GSONize所有值。如果您不想在课程中使用GSON,该怎么办? (我想我唯一的办法就是使用JVM序列化和上面的API将POJO保存为二进制流)。
我们到达那里:所以如果我们谈论的是独立附件: 如下所述,您可以这样做: InputStream in = db.find(....) 但是你真的必须努力提取附件。甚至最糟糕的是:您需要创建自己的新HTTP客户端(在我的代码片段中假设httpclient是已定义的Apache HTTP客户端实例)。
InputStream in = db.find(....)
if (in != null) {
// input stream will contain a JSON string
Object readFromJSON = readBinaryAttachment(in);
}
private Object readBinaryAttachment(InputStream in) throws IOException {
Object result = null;
JSONObject json = JSONObject.parse(in);
JSONObject attachments = (JSONObject)json.get(ATTACHMENTS_FIELD);
if (attachments != null) {
JSONObject attachment = (JSONObject)attachments.get(ATTACHMENT_FIELD_NAME);
if (attachment != null && attachment.get(CLOUDANT_ATTACHMENT_LENGTH_KEY) != null) {
String id = (String)json.get(CLOUDANT_ID_KEY);
HttpGet request = HttpUtil.createAuthenticatedGET(url+ "/"+ databaseName+ "/"+id+"/"+ATTACHMENT_FIELD_NAME, user, pass);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
Header contentType = entity.getContentType();
ObjectInputStream oins = null;
try {
if (contentType.getValue().equals(BINARY_MIME_TYPE)) {
InputStream ins = entity.getContent();
oins = new ObjectInputStream(ins);
result = oins.readUnshared();
} else {
throw new IOException("unexpected content type:"+contentType.getValue());
}
return result;
} catch (ClassNotFoundException ex) {
throw new IOException("unexpected object in attachment"+ex.getLocalizedMessage());
} finally {
EntityUtils.consumeQuietly(entity);
IOUtils.closeQuietly(oins);
}
}
} else {
throw new IOException("could not find attachments");
}
}
return null;
}
短暂的操作似乎太长了......
答案 0 :(得分:2)
在standalone attachments下的同一页面上,它会告诉您如何检索附件:
InputStream in = db.find( "doc_id/foo.txt");
您还可以将附件作为Base64编码的数据获取,如下所示:
Foo foo = db.find(Foo.class, "doc-id", new Params().attachments());
String attachmentData = foo.getAttachments().get("attachment.txt").getData();
答案 1 :(得分:0)
我们还没有在基础Lightcouch上面添加API以用于基础沙发功能(我们肯定会根据用户需求做...因此我可以为您打开一个问题)。如果有任何帮助,请查看https://github.com/cloudant/java-cloudant/blob/master/src/test/java/com/cloudant/tests/AttachmentsTest.java中的attachmentStandalone()
答案 2 :(得分:0)
你是对的:db.find(response.getId()+ ATTACHMENT_NAME)将完成这项工作。 感谢。