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

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

    As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:

        HttpPost req = new HttpPost(composeTargetUrl());
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
        try {
            entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        req.setEntity(entity);
    

    You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient

提交回复
热议问题