httpcomponent框架MultipartEntityBuilder addTextBody中文乱码
原创
©著作权归作者所有:来自51CTO博客作者passedbylove的原创作品,请联系作者获取转载授权,否则将追究法律责任
版本4.5.6
;
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", "先生,,,")服务器端一直乱码,显示很多问号???这是字符集问题。
// 使用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);
至此解析正确
正确: