java - 如何在 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 指针响应。
解决方案
您应该尝试将所有内容设置为 UTF-8
StringEntity urlparam = new StringEntity(param, StandardCharsets.UTF_8);
并添加适当的标题
httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
推荐阅读
- git - 将现有 SQL 代码添加到 Azure DevOps Git 并自动进一步部署到生产环境
- data-structures - 二叉搜索树搜索功能警告
- python - Python中类中声明的全局变量
- nuxt.js - 如何在 nuxt 中安装和配置 vee-validate (v4)?
- typescript - 如何使用 typescript 在 reduxtoolkit 中访问 getState() 到 slice reducer?
- python - 如何修复 Score 函数以使其与 GridsearchCV 一起使用,TypeError: score() 需要 2 个位置参数,但给出了 3 个
- java - 无法在 Dockerfile 中将 ARGUMENT 用于 ADD 命令
- big-ip - 如何识别在 iRule 中处理 HTTP_REQUEST 的池成员
- google-apps-script - 在 Google 表格中从左到右对列进行排序
- javascript - Angular - 无法等待可观察的订阅完成以执行 http 拦截器中的其余代码