简体   繁体   中英

I'm using this function in an app to post an image to the server using OkHttp3 in multipart/form-data

void postRequest() throws IOException {

    OkHttpClient client = new OkHttpClient();

    File file = new File(Environment.getExternalStorageDirectory().toString() + "/Image_ref.jpg");

    RequestBody requestbody = RequestBody.create(MultipartBody.FORM, file);

    Request request = new Request.Builder().
            addHeader("Authorization", "test").
            post(requestbody).
            url("MY_API").
            build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            call.cancel();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("TAG",response.body().string());
        }
    });
}

but I'm getting response saying

"The request content was malformed: Content-Type with a multipart media type must have a 'boundary' parameter.

Please let me know if I'm doing anything wrong and what is 'boundary' parameter and how to set it?

RequestBody requestbody = RequestBody.create(MultipartBody.FORM, file);

I would suggest try using , i use same to send images , and i send multiple images in one request using the below method

MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM); //this may not be needed 
multipartBodyBuilder.addFormDataPart("file", "Image_ref.jpg", RequestBody.create(MEDIA_TYPE, file) );

same request then can be used to do this

 try {
                                          Response response = oKclient.newCall(request).execute();

                                          line = response.body().string();

                                      }catch
                                              (Exception e ){
                                          e.printStackTrace();

                                      }

variable line will contains the body of the response , while response object is the actual response from the execution , below is my code showing how to add mutiple files at the same time , this is actually how i use it not very elegant but gets the job done

String order_data = "asdsd";
        String images = getImages(id); //my funciton returns a json array Stringified
        net.minidev.json.JSONArray fileArray = (net.minidev.json.JSONArray) net.minidev.json.JSONValue.parse(images);

        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.            setType(MultipartBody.FORM);
        multipartBodyBuilder.addFormDataPart("email", basicFunction.getUsername());
        multipartBodyBuilder.addFormDataPart("password", basicFunction.getPassword());

        multipartBodyBuilder.addFormDataPart("order_data",order_data);
        int filer = 0; // adding a php based filter this can be the php array counter
        MediaType MEDIA_TYPE = MediaType.parse("image/png" ); //
        for (Iterator<Object> flavoursIter = fileArray.iterator(); flavoursIter.hasNext();){
            net.minidev.json.JSONObject temp = (net.minidev.json.JSONObject) flavoursIter.next();
            String path = (String)temp.get("path");
            if(path.isEmpty() || path ==null ) continue;
            path = path.substring(6);
            // path = "fila://"+path;
            File file = new File(path);
            multipartBodyBuilder.addFormDataPart("file", "img.png", RequestBody.create(MEDIA_TYPE, file) );

// if only one files shows up you can use this code

//multipartBodyBuilder.addFormDataPart("file["+filer++"]", "img.png", RequestBody.create(MEDIA_TYPE, file) );

        }


        MultipartBody multipartBody = multipartBodyBuilder.build();



        Request request = new Request.Builder()
                .url("Url_to_use")
                .post(multipartBody)
                .build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM