使用volley返回null作为响应的多部分请求

时间:2016-05-17 09:52:57

标签: android

嗨我对android比较新,我使用多部分请求使用齐射将图像上传到服务器。图像正在正确上传,但我得到的响应为null。我检查了邮递员,我很奇怪地得到了正确的回复。

MultipartRequest.java

public class MultipartRequest extends Request<JSONObject> {


    private static final String FILE_PART_NAME = "user[avatar]";
    private long cacheTimeToLive = 0;
    private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    private final Response.Listener<JSONObject> mListener;
    private final File mImageFile;
    protected Map<String, String> headers;

    public MultipartRequest(String url, File imageFile, Listener<JSONObject> listener, ErrorListener errorListener){
        super(Method.PUT, url,errorListener);

        mListener = listener;
        mImageFile = imageFile;

        buildMultipartEntity();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = super.getHeaders();

        if (headers == null
                || headers.equals(Collections.emptyMap())) {
            headers = new HashMap<String, String>();
        }

        headers.put("Accept", "application/json");

        return headers;
    }

    private void buildMultipartEntity(){
        mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
        mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
    }

    @Override
    public String getBodyContentType(){
        String contentTypeHeader = mBuilder.build().getContentType().getValue();
        return contentTypeHeader;

    }

    @Override
    public byte[] getBody() throws AuthFailureError{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            mBuilder.build().writeTo(bos);
        } catch (IOException e) {
            VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
        }

        return bos.toByteArray();
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        JSONObject result = null;
        return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mListener.onResponse(response);

    }



}

uploadImage方法: -

private void uploadImage(final Bitmap bitmap){

        String name = "DP_"+ userName +".jpeg";
        try {
            file=bitmapToFile(name,bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MultipartRequest jsonRequest = new MultipartRequest( UPLOAD_URL,
                file,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                    Log.d(TAG,response.toString());



                        try {
                        //    parseUserPhotoResponse(response);
                            Picasso.with(getApplicationContext())
                                    .load(destination)
                                    .placeholder(R.mipmap.placeholder)
                                    .resize(avatarSize, avatarSize)
                                    .centerCrop()
                                    .transform(new CircleTransformation())
                                    .into(ivUserProfilePhoto);


                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "Error: " + volleyError.getMessage());
                        if(volleyError!=null)
                        {
                            try {
                                NetworkResponse networkResponse = volleyError.networkResponse;
                                if (networkResponse != null) {
                                    String responseBody = new String(volleyError.networkResponse.data, "utf-8");
                                    JSONObject jsonObject = new JSONObject(responseBody);
                                    Log.d(TAG, "Response body" + responseBody.toString());

                                    Log.d(TAG, jsonObject.toString());
                                    if (jsonObject.getBoolean("error") == false) {

                                    } else {
                                        Toast.makeText(getApplicationContext(), "" + jsonObject.getString("message"), Toast.LENGTH_LONG).show();
                                    }
                                }
                            } catch (JSONException e) {
                                //Handle a malformed json response
                            } catch (UnsupportedEncodingException error) {

                            }
                        }
                    }
                })
        ;

        //Creating a Request Queue

        jsonRequest.setShouldCache(false);

        MyApplication.getInstance().addToRequestQueue(jsonRequest, "UPLOAD_IMAGE");


    }

0 个答案:

没有答案