File upload with okhttp

前端 未结 4 1610
孤城傲影
孤城傲影 2020-12-06 02:54

Im finishing this project which is using okhttp for communication with a webservice.

All is going fine for regular GETs and POSTs, but I\'m not being able to properl

4条回答
  •  庸人自扰
    2020-12-06 03:34

    I found answer to my own question a bit after initial post.

    I´ll leave it here, because it can be useful to others, given that there is such a few okhttp upload examples around:

    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addFormDataPart("group", getGroup())
            .addFormDataPart("type", getType())
            .addFormDataPart("entity", Integer.toString(getEntity()))
            .addFormDataPart("reference", Integer.toString(getReference()))
            .addFormDataPart("task_file", "file.png", RequestBody.create(MediaType.parse("image/png"), getFile()))
                                                    .build();
    

    There is no reason to use "addPart" with "Headers.of" etc like in the recipes, addFormDataPart does the trick.

    And for the file field itself, it takes 3 arguments: name, filename and then the file body. That's it.

提交回复
热议问题