这是Android with php: Saving utf-8 string to MySQL的后续问题
我正在使用Android中的Gson库将类实例转换为JSON字符串。然后使用HttpPost将这个JSON字符串上传到一个PHP脚本,以将其保存到我的MySQL DB中。
起初我以为问题出在php或MySQL上,但现在看来是我的HttpPost代码序列没有正确地将JSON编码成UTF-8。如果我调试我的代码,并在Chrome中使用JSON字符串进行POST,它可以完美地工作。
我的UTF现在被格式化为MySQL -8 (utf8_general_ci)。
下面是我的HttpPost代码:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("questionnaire", json));
httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();问题可能出在httppost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));中,但我不确定如何通知我的PHP脚本我正在发送UTF-8格式的JSON。
例如,当Gson创建JSON strig时,Android将"can't get there“正确编码为"can/u0027t get there”。在上传JSON到PHP后,它被保存为"canu0027t get there“,在MySQL DB中没有"\”。
那么,我如何在Android中正确地标记/标记/识别这个JSON字符串为UTF-8格式,以便正确地保存它?
发布于 2012-10-09 21:09:41
在将json字符串保存到数据库之前,您必须在php代码中对其进行转义(例如mysql_real_escape_string())。你的Android代码是正确的。
发布于 2014-10-21 18:49:13
这就是解决方案:
StringEntity se = new StringEntity(jObjEnvio.toString(), HTTP.UTF_8);如果这不工作,做清洁和修复项目。
https://stackoverflow.com/questions/12799868
复制相似问题