1

I am using StringRequest to send the Files to server. I am using the following code:

final MultipartEntityBuilder mHttpEntity = buildMultipartEntity(files_to_upload, params);

        Response.Listener<String> rListner = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response != null) {
                    Intent intent = new Intent(Constants.ACTION_RESPONSE_RECEIVED);
                    intent.putExtra(Constants.RESPONSE, response);
                    intent.putExtra(SignupActivity.EXTRA_ACTION_RESPONSE, SignupActivity.EXTRA_SIGNUP_DATA);
                    LocalBroadcastManager.getInstance(MyApplication.getContext()).sendBroadcast(intent);
                }
            }
        };

        Response.ErrorListener errorListner = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Intent intent = new Intent(Constants.ACTION_RESPONSE_RECEIVED);
                LocalBroadcastManager.getInstance(MyApplication.getContext()).sendBroadcast(intent);
                if(error != null && error.getMessage() != null) {
//                    Toast.makeText(MyApplication.getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
                else {
                    Log.i(TAG, "postRequestToServer: onErrorResponse : error message null");
                }
            }
        };

        StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, url, rListner, errorListner)
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }

//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                return params;
//            }

            @Override
            public String getBodyContentType() {
                return mHttpEntity.build().getContentType().getValue();
            }
//
            @Override
            public byte[] getBody() throws AuthFailureError {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                try {
                    mHttpEntity.build().writeTo(bos);
                } catch (IOException e) {
                    VolleyLog.e("IOException writing to ByteArrayOutputStream");
                }
                return bos.toByteArray();
            }
        };

private MultipartEntityBuilder buildMultipartEntity(String files_to_upload, HashMap<String, String> params) {

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        String[] arr_files = files_to_upload.split("##");
        for(int i = 0; i < arr_files.length; i++) {
            String filePath = arr_files[i];
            if(filePath == null || filePath.length() == 0)
                continue;
            File file = new File(filePath);
            String extension = MimeTypeMap.getFileExtensionFromUrl(arr_files[i]);
            String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

            builder.addBinaryBody("userfile", file, ContentType.create(mimeType), file.getName());
//            builder.addPart("userfile", new FileBody(file));
        }

        try {
            for (String key: params.keySet())
                builder.addPart(key, new StringBody(params.get(key)));
        } catch (UnsupportedEncodingException e) {
            VolleyLog.e("UnsupportedEncodingException");
        }

        return builder;
    }

But the issue is getParams is not being called. Server is expecting paramters, I tried to send using EntityBuilder but still I am having errors in sending the parameters.

Can anyone please let me know how can I upload files using StringRequest with Parameters?

Mrunal
  • 348
  • 4
  • 15
Mustansar Saeed
  • 2,730
  • 2
  • 22
  • 46
  • As far as I understood your question:: When you use Volley to make a `StringRequest`, you are making an HTTP GET, expecting tex/plain as response... When you change to a POST, [you can check this link](http://stackoverflow.com/a/16795805/4903925) for related content... – Bonatti Apr 07 '16 at 11:23
  • No, I using post to send the data. `getParams` is not being called when I override `getBody()` How to make request with `Parameters` – Mustansar Saeed Apr 07 '16 at 11:24

2 Answers2

0

Your getParams() is not getting called because StringRequest.java inherits from Request.java. Now in Request.java, if you look at the getBody() method,

public byte[] getBody() throws AuthFailureError {
        Map<String, String> params = getParams();
        if (params != null && params.size() > 0) {
            return encodeParameters(params, getParamsEncoding());
        }
        return null;
    }

you can see getParams() is getting called from getBody() method. Now while making your request StringRequest jsonObjectRequest, you are overriding the getBody() method which means your getParams() will not get called. This is the reason why getParams() is not getting called.

EDIT Create this custom volley request class that takes params inside the request constructor

public class CustomRequest extends Request<String> {

    private Listener<String> listener;
    private Map<String, String> params;

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<String> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(String response) {
        listener.onResponse(response);
    }
}

Now send your request through this class. instead of overriding getParams(), just create a hashmap for your params, and pass them inside the constructor.

Ankit Aggarwal
  • 5,317
  • 2
  • 30
  • 53
0

Use getparams and getHeader metods:

@Override
protected Map<String, String> getParams() throws AuthFailureError {
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("product_id", "4");
    parameters.put("count", Productcount.getText().toString());
    parameters.put("type", cashstatus);
    parameters.put("description", "Matn bo'ladi");
    parameters.put("phone_number", "946287009");
    parameters.put("on_map", address);
    return parameters;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Authorization", "Bearer " + token);
    return headers;
}
Jérémie Bertrand
  • 3,025
  • 3
  • 44
  • 53
Fakhriddin Abdullaev
  • 4,169
  • 2
  • 35
  • 37