我正在使用Volley将具有JSON负载的Base64编码图像上传到HelpScout server。这会返回 com.android.volley.ServerError 和状态码400 。我将图像编码如下:
var imageEncoded = ""
try {
val bitmap = MediaStore.Images.Media.getBitmap(context?.contentResolver, uri)
//val bitmap = BitmapFactory.decodeFile(path)
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream)
val imageBytes = stream.toByteArray()
imageEncoded = Base64.encodeToString(imageBytes, Base64.DEFAULT)
} catch (e: Exception) {
e.printStackTrace()
}
我已经检查了几个提出的问题,但是没有运气。以下是我正在使用的Volley方法:
public static void volleyRowJsonPostRequest(Context context,String url, JSONObject object,final Map<String, String> headers, final VolleyTaskListener taskListener) {
final JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
taskListener.onTaskComplete(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null)
taskListener.onTaskFailed(networkResponse.statusCode);
}
}
){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
};
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsObjRequest.setShouldCache(false);
Volley.newRequestQueue(context).add(jsObjRequest);
}
和JSONObject如下:
{
"subject": "some test value",
"mailboxId": 170715,
"type": "email",
"status": "active",
"customer": {
"email": "mymailaddress@mail.com"
},
"threads": [
{
"type": "customer",
"text": "some test value",
"customer": {
"email": "mymailaddress@mail.com"
},
"attachments": [
{
"fileName": "Screenshot_20181005-160109.png",
"mimeType": "image\/png",
"data": "base64 encoded string goes here"
}
]
}
],
"tags": [
"Swytch",
"Help"
]
}
答案 0 :(得分:1)
我已修复了仅将Base64编码方法从Base64.encodeToString(imageBytes, Base64.DEFAULT)
更新为Base64.encodeToString(imageBytes, Base64.NO_WRAP)
的错误。使用 Base64.DEFAULT 时,生成的编码字符串是编码器标志的默认值(包括换行符)。 Base64.NO_WRAP 编码器标志位,可省略所有行终止符(即,输出将在一条长行上)。 Here是更多信息。