post 中文数据到elasticsearch restful接口报json_parse_exception 问题
2024-08-22 21:12:41
我们的客户端程序直接调用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"));
问题解决
最新文章
- JavaScript事件概览
- 【JavaScript忍者秘籍】
- AndroidManifest.xml的android:name是否带.的区别
- android自定义控件(8)-利用onMeasure测量使图片拉伸永不变形,解决屏幕适配问题
- iOS学习12之OC属性和点语法
- node环境配置安装(nvm)
- 3163: [Heoi2013]Eden的新背包问题
- 几组User-Agent
- Pro Git(中文版)
- Problem 1014 xxx游戏 暴力+拓扑排序
- VBA Excel 单元格操作
- Asp.Netserver控件开发的Grid实现(三)列编辑器
- 新服务器部署sqlserver之前的准备
- Thread类常用方法
- Java设计模式:工厂模式
- itchat 微信的使用
- work behind corp proxy
- transform: translate(-50%, -50%) 实现块元素百分比下居中
- python第三十天-类
- Python 读取目录、文件
热门文章
- 安装mysql,mysql创建数据库,创建用户及为用户添加权限
- <;xsd:import>;
- ASI 实现注册方法的小例子(get和post方式)
- linux C 内存分配(~道的光芒四射~)
- 关于epoll的IO模型是同步异步的一次纠结过程
- .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.”
- linux shell except tcl login ssh Automatic interaction
- ubuntu下设置电脑为WiFi热点
- [LeetCode&;Python] Problem 589. N-ary Tree Preorder Traversal
- python3获取当前目录和上级目录