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

后端 未结 9 2323
不思量自难忘°
不思量自难忘° 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:26

    A very simple approach for the dev who just want to send POST parameters in multipart request.

    Make the following changes in class which extends Request.java

    First define these constants :

    String BOUNDARY = "s2retfgsGSRFsERFGHfgdfgw734yhFHW567TYHSrf4yarg"; //This the boundary which is used by the server to split the post parameters.
    String MULTIPART_FORMDATA = "multipart/form-data;boundary=" + BOUNDARY;
    

    Add a helper function to create a post body for you :

    private String createPostBody(Map params) {
            StringBuilder sbPost = new StringBuilder();
            if (params != null) {
                for (String key : params.keySet()) {
                    if (params.get(key) != null) {
                        sbPost.append("\r\n" + "--" + BOUNDARY + "\r\n");
                        sbPost.append("Content-Disposition: form-data; name=\"" + key + "\"" + "\r\n\r\n");
                        sbPost.append(params.get(key).toString());
                    }
                }
            }
            return sbPost.toString();
        } 
    

    Override getBody() and getBodyContentType

    public String getBodyContentType() {
        return MULTIPART_FORMDATA;
    }
    
    public byte[] getBody() throws AuthFailureError {
            return createPostBody(getParams()).getBytes();
    }
    

提交回复
热议问题