首页 > 解决方案 > 如何在 CloseableHttpClient APi 中编码 Post Data JSON

问题描述

我使用 CloseableHttpClient APi 进行 Post 调用,使用 Basic Auth 进行授权

private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");

MyJson myJson = new MyJson(); //custom java object to be posted as Request Body
Gson gson = new Gson();
String param = gson.toJson(myJson);
StringEntity urlparam = new StringEntity(param);

String credentials = username + ":" + passwprd;
String base64Credentials = new String(Base64.getencoder().encode(credentials.getBytes()));
String authorizartionHeader = "Basic" + base64Credentials;


httppost.setHeader("Content-Type", "application/Json");
httppost.setHeader("Authorization", authorizartionHeader);
urlparam.setContentEncoding("UTF-8");
httppost.setEntity(urlparam);
httpclient.execute(httppost);

我收到错误

“无效的 UTF-8 中间字节”

我已经对 JSON 进行了编码,但该编码不适用于除英语之外的其他语言环境。如何对 Post 数据进行编码。

我尝试使用该方法 httppost.setEntity(new URLEncodedFormEntity(namevaluePair, "UTF-8")),但我没有任何 Namevaluepair 并且如果在其中添加 Username-pswd 则获得 Null 指针响应。

标签: javarestpost

解决方案


您应该尝试将所有内容设置为 UTF-8

StringEntity urlparam = new StringEntity(param, StandardCharsets.UTF_8);

并添加适当的标题

httppost.setHeader("Content-Type", "application/json;charset=UTF-8");

推荐阅读