Home > Blockchain >  OKHTTP Android sending POST request as formdata with image
OKHTTP Android sending POST request as formdata with image

Time:01-15

I have an API POST request that takes in form/data with both text (strings) and 1 image file. In postman, this is what it looks like, and it works perfectly :)

POST Request on postman that works by taking in form/data strings and an image

I am trying to send the same thing through a POST request on an android app through OKHTTP. Here is the code that I wrote:

        MediaType mediaType = MediaType.parse(getMimeType(imageFile.toURI().toURL().toString()));
        requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("imageFile", imageFile.getName(), RequestBody.create(imageFile, mediaType))
                .addFormDataPart("machineKey", machineKey)
                .addFormDataPart("authToken", authToken)
                .addFormDataPart("UIID", UIID)
                .addFormDataPart("localItemID", localItemID)
                .addFormDataPart("itemName", itemName)
                .addFormDataPart("itemDescription", itemDescription)
                .addFormDataPart("itemPrice", itemPrice)
                .addFormDataPart("itemStock", itemStock)
                .addFormDataPart("itemAge", itemAge)
                .build();
    Request request = new Request.Builder()
            .url(URLString)
            .post(requestBody)
            .build();
    System.out.println("POST: calling: "  URLString);
    Response response = client.newCall(request).execute();

Here are a few notes to keep in mind :)

  1. imageFile is the file if the image (and the file is guaranteed to always exist, and is accessible)

  2. all strings are never null

    (getMimeType(imageFile.toURI().toURL().toString()) will return "image/jpeg" or "image/*", I have tried both

I am running this code asynchronously, and this code will post the string values correctly, but for some reason will not correctly post the image file. Any ideas? Thanks!

CodePudding user response:

You are missing to set the content-type request header: .addHeader("content-type", "multipart/form-data")

CodePudding user response:

Actually figured it out... turns out the files names I were sending were not sanitized, so some files being sent had illegal characters in its file name, so I got that fixed! thanks! :)

  •  Tags:  
  • Related