版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiejunna/article/details/86610270
问题描述:数据通过tddl(tddl:数据库中间件,通过http请求方式,把数据间距存入数据库)存入redis和http请求方式存入es,用到了apache发送请求的jar包,存数据之前,debug模式下,中文没有乱码,是正常编码,存入redis、es后,发现中文乱码,是一串问号。
解决办法:创建请求时,指定StringEntity
编码集
代码示例如下:
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
@Component
public class RequestTools {
private Logger logger = LoggerFactory.getLogger(RequestTools.class);
private String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
private final String DEF_CHATSET = "UTF-8";
private final int DEF_CONN_TIMEOUT = 30000;
private final int DEF_READ_TIMEOUT = 30000;
/**
* 请求es插入数据操作,参数为字符串,post请求
* @param url
* @param str json格式的字符串
* @return 成功:{"_index":"geofencing","_type":"weblocation","_id":"AWhwcUT7RCuwyAS_S4C4",
* "_version":1,"result":"created","_shards":{"total":1,"successful":1,"failed":0},"created":true}
*/
public JSONObject netEsRequestSave(String url,String str){
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.addHeader("Authorization",getToken());
JSONObject response = null;
try {
String mimeType = "application/json";
//处理中文乱码问题
ContentType contentType = ContentType.create(mimeType,"UTF-8");
StringEntity s = new StringEntity(str,contentType);
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
logger.info("res code:",res.getStatusLine().getStatusCode());
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED){
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.fromObject(result);
logger.info("es插入数据返回结果:",response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
}