我想从我的Android设备向服务器发送一个json对象(在帖子中)。
在我的json对象中,我需要在Base64中添加一个图像。我不能使用String将我的图像转换为Base64,因为String太短而不能包含Base64编码的文件。 我必须使用BytesArray。
如何将类似内容发送到JSON Web服务?
{
"emergency":"gsjqsbl",
"cod_valid":"O",
"image":{
"content":"/9j/4AAQSkZJRg ## MY VERY VERY VERY VERY VERY VERY VERY LONG IMAGE IN BASE64 ## BWNn+SV5H8KQADnn9ysrKA1EVX+lNDkSJ8ai8UADCLoAR3TWVlHT95AVvcfwCvD4Hq1joP5NX3Ciat7zyP4VlZW9bnl1sf//Z",
"content_type":"image/jpg"
},
"indoor":"yes",
"access_conditional":"text",
"geo_shape":{
"type":"Point",
"coordinates":[
2.0202024,
45.799005
]
},
"lastupdate":"",
"ref_fr_sdis91":"",
"name":"TEST IN UPPERCASE WITH SPECIAL CHARACTERS ;/*-é@$~æ€",
"geo_point_2d":"45.799005,2.0202024",
"source":"soures",
"objectid":"",
"aed_location":"Spopopo"
}
我真的不能使用String。
由于
编辑:我还做了什么:
//output stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//write text
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write("json start { blabla: value");
//Write image
AssetManager assetManager = context.getAssets();
InputStream istr;
Bitmap bitmap = null;
try {
istr = assetManager.open("pictures/defib12.jpg");
bitmap = BitmapFactory.decodeStream(istr);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
outputStream.write(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
//write text
OutputStreamWriter outputStreamWriter2 = new OutputStreamWriter(outputStream);
bufferedWriter = new BufferedWriter(outputStreamWriter2);
bufferedWriter.write("json end }");
HttpResponse response = restClient.executePostRequest(pushUrl, outputStream);
并且:
public HttpResponse executePostRequest(String url, ByteArrayOutputStream outputStream) throws IOException {
LogWrapper.debug(DmaRestClient.class, "New HttpPost request: " + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(outputStream.toByteArray()));
request.setHeader("Content-Type", "application/json");
return client.execute(request);
}
答案 0 :(得分:0)
你应该使用lib来做到这一点。检查Genson,它提供了两种ser / de二进制内容的机制:使用经典的base64编码字符串(但在你的情况下,看起来它不会工作)或 ser / de作为数组整理。请注意,您必须在服务器端使用相同的机制 - 但它可能是支持此类格式的另一个库。
使用Genson,您将创建表示json的类,image.content值将是字节数组。要在Genson中启用此选项:
Genson genson = new GensonBuilder().useByteAsInt(true).create();
genson.serialize(yourObject, theOutputStream);
如果您想在不使用任何库的情况下手动完成,您仍然可以(但这是一种不好的做法 ...)使用相同的技巧=>将字节数组Ser / de作为int数组。