如何在CloseableHttpClient APi中编码Post Data JSON



我使用CloseableHttpClient APi进行Post调用,并使用基本身份验证进行授权

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")),但我没有任何Name-valuepair,如果在其中添加Username pswd,则会得到Null指针响应。

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

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

并添加适当的标题

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

最新更新