How to suppress Charset being automatically added to Content-Type in okhttp

前端 未结 2 936
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 01:05

Consider the following code:

    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse(\"text/plain; charset=utf-8\"); // [A]
         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 01:58

    I found the solution:

    The following line is the culprit:

    RequestBody body = RequestBody.create(mediaType, media);
    

    create has 3 signatures for media:

    • String
    • byte[]
    • File

    When I pass a String, it disregards the supplied mediaType and adds the charset to it. Even for image/jpeg it would send

    image/jpeg; charset=utf-8

    to the server.

    Using byte[] or File suppresses that behavior.

    I hope this helps you!

    [Stupid me - for simplicity I gave it a String during testing, as I didn't care about the body ;-( ]

提交回复
热议问题