0

Hi I am relatively new to android, I have used multipart request to upload an image to server using volley. The image is being uploaded correctly but I am getting the response as null. I checked on postman, I am strangely getting the correct response there.

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 method :-

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");


    }
Jay Rathod
  • 11,131
  • 6
  • 34
  • 58
  • onResponse has null response ? – Shubhank May 17 '16 at 09:55
  • Check I already have found the solution. In multipart, you have to manually make body of the data you need to send. Check this out http://stackoverflow.com/questions/32796770/upload-image-via-volley-throwing-error-having-array-of-image-and-array-of-text – Jimit Patel May 17 '16 at 09:56
  • see my answer [here](http://stackoverflow.com/questions/36513174/android-multipart-image-upload-with-httpconnectionparams-deprecated-in-new-api/36513504#36513504) – mehrdad khosravi May 17 '16 at 09:56
  • yes it is giving null as response – Alankrita Sood May 17 '16 at 09:57
  • Try with MultipartUtility class -->>https://github.com/ndexbio/ndex-java-client/blob/master/src/main/java/org/ndexbio/rest/client/MultipartUtility.java – Ram Prakash Bhat May 17 '16 at 10:51

0 Answers0