【发布时间】:2019-11-19 15:22:53
【问题描述】:
我在编码图像以将其发送到 json 文件时遇到问题。如果我将图像字符串提取到 txt 并对其进行解码,它可以正常工作并且我可以看到编码的图像,但是当我将其放入 json 文件时,图像字符串在遇到“/”时会发生变化,它将其转换为“\ / " 到 json 文件中,如果图像字符串更改行,则 json 文件添加 "\n"。这使得从 json 文件中提取图像字符串以查看图像是不可能的。
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
Bitmap bitmap2 = ((BitmapDrawable) secondImageV.getDrawable()).getBitmap();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
imageString2 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
sendPost(imageString1,imageString2,sendAlert);
public void sendPost(String im1, String im2, String alert) {
JSONObject json = new JSONObject();
try {
json.put("name", compname.getText());
json.put("hydrovalue", _hydrometerValue.getText());
json.put("im1", im1) ;
json.put("im2", im2);
json.put("hydrohealth", check1);
json.put("hydrorepair", check2);
json.put("hydroalert", alert);
json.put("stime", stime.getText());
json.put("etime", etime.getText());
json.put("comm", _comments.getText());
} catch (JSONException e) {
e.printStackTrace();
}
String url = "https://api.myjson.com/bins/lmz8i";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "String Response : " + response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error getting response", Toast.LENGTH_LONG).show();
}
});
【问题讨论】:
-
Base64.encodeToString(imageBytes2, Base64.NO_WRAP);应该处理意外的换行。如果值在 json 文本中被双引号引起来,/(也可能是+)的转义是没有意义的。转义只对非标准 ID 有意义。