Search code examples
androidmultipartokhttp

MediaType with additional info


When creating an Multipart/related request. We need add an additional type=MIME_TYPE to the Content-Type string

The Content-Type should look like this

Content-Type: multipart/related; boundary=boundary_1324; type="application/json";

When Looking at the MultipartBody constructor

MultipartBody(ByteString boundary, MediaType type, List<Part> parts) {
    this.boundary = boundary;
    this.originalType = type;
    this.contentType = MediaType.parse(type + "; boundary=" + boundary.utf8());
    this.parts = Util.immutableList(parts);
  }

We are allowed to add the boundary token.

But when calling MediaType.parse like this

final MediaType parse = MediaType.parse("multipart/related; type=application/json");

The object parse is null.

Anyone got an idea on how to add type=application/json?


Solution

  • Quote the value, and don't include the trailing ;

    MediaType mt = MediaType.parse("multipart/related; type=\"application/json\"");
    

    This matches the spec, which expects either a simple token or a quoted string. https://www.rfc-editor.org/rfc/rfc2045#section-5.1

    n.b. MediaType won't extract type for you, but shouldn't fail.