httpcomponent框架MultipartEntityBuilder addTextBody中文乱码

版本4.5.6

   String url = "https://172.16.3.50:8111/api/tts/offline";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("User-Agent", "Mozilla/5.0 巧妙欺骗过浏览器Agent");
        httpPost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        httpPost.addHeader("Accept-Encoding", "gzip, deflate");
        httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");

        ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), StandardCharsets.UTF_8);
        StringBody stringBody = new StringBody("先生,这是您的咖啡,请慢慢享用",contentType);


        HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532)
                .addPart("text",stringBody)
                .addTextBody("speakerId", "person_2")
                .addTextBody("speed", "1.5")
                .addTextBody("pitch", "1.2")
                .addTextBody("volume", "1")

                .build();

        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);

        HttpEntity entity = resp.getEntity();
        System.out.println(entity);

之前使用.addTextBody("text", "先生,,,")服务器端一直乱码,显示很多问号???这是字符集问题。

在网上找到了一份答案:https://blog.csdn.net/kufeiyun/article/details/45172563

// 使用addPart+ StringBody代替addTextBody,解决中文乱码

// builder.addTextBody(entry.getKey(), entry.getValue());

ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
StringBody stringBody = new StringBody(entry.getValue(),contentType);
builder.addPart(entry.getKey(), stringBody);

至此解析正确

正确:

原文地址:https://www.cnblogs.com/passedbylove/p/12017712.html