我有一个使用Volley的多部分请求。我第一次使用这个库,需要将图像发送到服务器并获得一个数组作为回报。这是我怎么做的?你能提出什么建议吗?如果做得对,我担心结构。提前致谢。这是我的代码: 我收到ServerError
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] byteArray, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Request.Method.POST, url, errorListener);
this.mListener = errorListener;
this.listener = listener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = byteArray;
buildMultipartEntity();
}
private void buildMultipartEntity() {
ContentType contentType = ContentType.create("image/jpeg");
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addBinaryBody("image", this.mMultipartBody,contentType, "image.jpg" );
mHttpEntity = multipartEntity.build();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
@Override
public String getBodyContentType() {
return mHttpEntity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mHttpEntity.writeTo(bos);
} catch (IOException e) {
e.printStackTrace();
}
return bos.toByteArray();
}
@Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(NetworkResponse response) {
}
@Override
public void deliverError(VolleyError error) {
mListener.onErrorResponse(error);
}
}
public void postImage(byte[] byteArray, VolleyResponseHandler volleyResponseHandler, final Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
MultipartRequest multipartRequest = new MultipartRequest(ApplicationConstants.BASE_URL, null, null, byteArray, new Response.Listener<String>() {
@Override
public void onResponse(String result){
ArrayList<String> listItems = new ArrayList<>();
try {
JSONObject response = new JSONObject(result);
JSONArray jsonArray = response.getJSONArray("array");
for(int i = 0; i < jsonArray.length(); i++){
listItems.add(jsonArray.get(i).toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.v("error", error.toString());
});
multipartRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(multipartRequest);
这是我需要解析的响应
{
“array”: [
“one”,
“two”,
“three”
]
}