How to send a “multipart/form-data” POST in Android with Volley

后端 未结 9 2177
不思量自难忘°
不思量自难忘° 2020-11-22 03:50

Has anyone been able to accomplish sending a multipart/form-data POST in Android with Volley yet? I have had no success trying to upload an image/png

9条回答
  •  渐次进展
    2020-11-22 04:18

    First answer on SO.

    I have encountered the same problem and found @alex 's code very helpful. I have made some simple modifications in order to pass in as many parameters as needed through HashMap, and have basically copied parseNetworkResponse() from StringRequest. I have searched online and so surprised to find out that such a common task is so rarely answered. Anyway, I wish the code could help:

    public class MultipartRequest extends Request {
    
    private MultipartEntity entity = new MultipartEntity();
    
    private static final String FILE_PART_NAME = "image";
    
    private final Response.Listener mListener;
    private final File file;
    private final HashMap params;
    
    public MultipartRequest(String url, Response.Listener listener, Response.ErrorListener errorListener, File file, HashMap params)
    {
        super(Method.POST, url, errorListener);
    
        mListener = listener;
        this.file = file;
        this.params = params;
        buildMultipartEntity();
    }
    
    private void buildMultipartEntity()
    {
        entity.addPart(FILE_PART_NAME, new FileBody(file));
        try
        {
            for ( String key : params.keySet() ) {
                entity.addPart(key, new StringBody(params.get(key)));
            }
        }
        catch (UnsupportedEncodingException e)
        {
            VolleyLog.e("UnsupportedEncodingException");
        }
    }
    
    @Override
    public String getBodyContentType()
    {
        return entity.getContentType().getValue();
    }
    
    @Override
    public byte[] getBody() throws AuthFailureError
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try
        {
            entity.writeTo(bos);
        }
        catch (IOException e)
        {
            VolleyLog.e("IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }
    
    /**
     * copied from Android StringRequest class
     */
    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }
    
    @Override
    protected void deliverResponse(String response)
    {
        mListener.onResponse(response);
    }
    

    And you may use the class as following:

        HashMap params = new HashMap();
    
        params.put("type", "Some Param");
        params.put("location", "Some Param");
        params.put("contact",  "Some Param");
    
    
        MultipartRequest mr = new MultipartRequest(url, new Response.Listener(){
    
            @Override
            public void onResponse(String response) {
                Log.d("response", response);
            }
    
        }, new Response.ErrorListener(){
    
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley Request Error", error.getLocalizedMessage());
            }
    
        }, f, params);
    
        Volley.newRequestQueue(this).add(mr);
    

提交回复
热议问题