我们的客户端程序直接调用es 的restful接口, 通过post json数据去查询, 但post数据有中文的时候,有些中文会报异常,有些中文不会

{"error":{"root_cause":[{"type":"json_parse_exception","reason":"Invalid UTF-8 middle byte 0x5c\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@58cf272c; line: 1, column: 238]"}],"type":"json_parse_exception","reason":"Invalid UTF-8 middle byte 0x5c\n at [Source: org.elasticsearch.transport.netty4.ByteBufStreamInput@58cf272c; line: 1, column: 238]"},"status":500}

而通过es head插件去post 同样的json数据,却运行正常,  初步判断写数据的时候有问题, 上代码

   

URL url = new URL(esURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
//connection.setConnectTimeout(30000);// 超时时间设置为30秒
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Charsert", "UTF-8");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); connection.connect(); // POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(query);

问题就出在wirteBytes()方法里,我们看JDK源代码

public final void writeBytes(String s) throws IOException {
int len = s.length();
for (int i = 0 ; i < len ; i++) {
out.write((byte)s.charAt(i));
}
incCount(len);
}

我们知道UTF8编码里一个中文用3个字节来存储,而这里是直接把一个中文强制转一个byte, 这样肯定会有问题的

修改代码成

out.write(query.getBytes("UTF-8"));

问题解决

最新文章

  1. JavaScript事件概览
  2. 【JavaScript忍者秘籍】
  3. AndroidManifest.xml的android:name是否带.的区别
  4. android自定义控件(8)-利用onMeasure测量使图片拉伸永不变形,解决屏幕适配问题
  5. iOS学习12之OC属性和点语法
  6. node环境配置安装(nvm)
  7. 3163: [Heoi2013]Eden的新背包问题
  8. 几组User-Agent
  9. Pro Git(中文版)
  10. Problem 1014 xxx游戏 暴力+拓扑排序
  11. VBA Excel 单元格操作
  12. Asp.Netserver控件开发的Grid实现(三)列编辑器
  13. 新服务器部署sqlserver之前的准备
  14. Thread类常用方法
  15. Java设计模式:工厂模式
  16. itchat 微信的使用
  17. work behind corp proxy
  18. transform: translate(-50%, -50%) 实现块元素百分比下居中
  19. python第三十天-类
  20. Python 读取目录、文件

热门文章

  1. 安装mysql,mysql创建数据库,创建用户及为用户添加权限
  2. &lt;xsd:import&gt;
  3. ASI 实现注册方法的小例子(get和post方式)
  4. linux C 内存分配(~道的光芒四射~)
  5. 关于epoll的IO模型是同步异步的一次纠结过程
  6. .Net EF Core数据库使用SQL server 2008 R2分页报错How to avoid the “Incorrect syntax near &#39;OFFSET&#39;. Invalid usage of the option NEXT in the FETCH statement.”
  7. linux shell except tcl login ssh Automatic interaction
  8. ubuntu下设置电脑为WiFi热点
  9. [LeetCode&amp;Python] Problem 589. N-ary Tree Preorder Traversal
  10. python3获取当前目录和上级目录