Android HttpPost數據中文亂碼的解決方案 – Android移動開發技術文章_手機開發 Android移動開發教學課程

在項目中,以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; 

摘自 心靈凈土

發佈留言