/** * * @Description: http://xxx/m/studyguidenotesbackup/bookContent.json?token=xxx&bookContent=xxx&bookContentID=xxx * @param userToken * @param sermonId * @param sermonContent * @return * @author: J * @date: 2015-9-19 * @version: TODO */ public static SermonNoteBackupResultVO uploadSermonToBackendServer(String userToken, String sermonId, String sermonContent) { String uploadSermonToBackendServerURLPath = ConstantUtil.DOMAIN + "/m/studyguidenotesbackup/bookContent.json"; HttpPost postUploadSermonBackup = new HttpPost(); HttpClient clientUploadSermonBackup = new DefaultHttpClient(); BufferedReader reader = null; List<NameValuePair> params = new ArrayList<NameValuePair>(); SermonNoteBackupResultVO sermonNoteBackupResultVO = null; try { postUploadSermonBackup.setURI(new URI(uploadSermonToBackendServerURLPath)); params.add(new BasicNameValuePair("token", userToken)); params.add(new BasicNameValuePair("bookContent", sermonContent)); params.add(new BasicNameValuePair("bookContentID", sermonId)); postUploadSermonBackup.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); postUploadSermonBackup.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); HttpResponse response = clientUploadSermonBackup.execute(postUploadSermonBackup); reader = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); StringBuffer strBuffer = new StringBuffer(""); String line = null; while ((line = reader.readLine()) != null) { strBuffer.append(line); } sermonNoteBackupResultVO = GsonParse.getObjResult(strBuffer.toString(), SermonNoteBackupResultVO.class); }catch (Exception e) { e.printStackTrace(); }finally { if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } return sermonNoteBackupResultVO; }
以上代码是我修改过的代码,不会出现乱码了,下面和大家分享下解决这个问题的心得体会。
问题描述:因为项目初期一直是支持英文的,所以这块也没考虑过中文或者其他国家的文字会出现乱码的情况,不巧遇到一个越南客户,越南文出现了乱码。
排查问题,客户端和服务器端都已经设置了UTF-8的编码模式,但是服务器端收到的Android端的备份文件还是乱码,但是IOS端确是正常的,有点迷茫之下开始查找解决方案。
Android和ios同时打印Http请求的头部,发现问题所在:
Andorid : content-type:application/x-www-form-urlencoded;
IOS : content-type:application/x-www-form-urlencoded; charset=utf-8;
OK.找到问题解决之即可。
在Android客户端Post请求的时候加上:postUploadSermonBackup.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.