Android HttpPost数据中文乱码的解决方案
在项目中,以HttpPost方式向服务器上提交数据时,服务器上中文竟然显示乱码,针对该种情况证明解决呢?其实,这样的问题,在架构的时候,就应该考虑到,如果牵扯到各个不同的平台应用,尽量统一使用UTF8编码,可以少很多麻烦。当然在post数据的时候,可以指定编码,请参阅下面的函数:
·
[java] public Map<String, Object> CreateNote(int albumId, String title,
String remark) {
String noteId = "";
Map<String, Object> map = new HashMap<String, Object>();
try {
HttpParams parms = new BasicHttpParams();
parms.setParameter("charset", HTTP.UTF_8);
HttpConnectionParams.setConnectionTimeout(parms, 8 * 1000);
HttpConnectionParams.setSoTimeout(parms, 8 * 1000);
HttpClient httpclient = new DefaultHttpClient(parms);
HttpPost httppost = new HttpPost(ConfigHelper.CreateUri);
httppost.addHeader("Authorization", mToken);
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("charset", HTTP.UTF_8);
JSONObject obj = new JSONObject();
obj.put("title", title);
obj.put("categoryId", mCategoryId);
obj.put("sourceUrl", GetSourceUri());
JSONArray arr = new JSONArray();
arr.put(DateFormat.format("yyyyMM",Calendar.getInstance(Locale.CHINA)));
obj.put("tags", arr);
obj.put("content", remark);
httppost.setEntity(new StringEntity(obj.toString(), HTTP.UTF_8));
HttpResponse response;
response = httpclient.execute(httppost);
int code = response.getStatusLine().getStatusCode();
if (code == ConstanDefine.ErrorCode.SuccOfHttpStatusCode) {
String rev = EntityUtils.toString(response.getEntity());
obj = new JSONObject(rev);
noteId = obj.getString("id");
map.put("return_code", "0");
map.put("content", rev);
}
} catch (Exception e) {
if (map.containsKey("return_code")) {
map.remove("return_code");
}
map.put("return_code", "1");
}
return map;
}
摘自 心灵净土
补充:移动开发 , Android ,