如何在 CloseableHttpClient APi 中编码 Post 数据 JSON

How to encode Post Data JSON in CloseableHttpClient APi

我已经使用 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);

我遇到错误

"Invalid UTF-8 middle byte"

我已经对 JSON 进行了编码,但该编码对于英语以外的其他语言环境仍然不起作用。如何编码 Post 数据。

我试过用这个方法 httppost.setEntity(new URLEncodedFormEntity(namevaluePair, "UTF-8")) 但我没有任何名称值对,如果在其中添加用户名密码,则会收到空指针响应。

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

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

并添加适当的header

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