用UTF8文本POST自带ASCII

问题描述:

我用这段代码打4个小时,也许我做错了什么。 “文本”来到服务器像“????”用UTF8文本POST自带ASCII

error_log(mb_detect_encoding($_POST['text'])) 

它给了我ASCII:

我已经检查了日志。

/** 
    * Send the question to the server 
    */ 
    private void sendQuestion() { 
     final String uid = getContext().getSharedPreferences(LoginActivity.PREFS_NAME, 0).getString("uid", "0"); 
     final String text = ((EditText) findViewById(R.id.question_et)).getText().toString(); 

     final MultipartEntity multipartEntity = new MultipartEntity(); 

     if (mFile != null) { 
      final FileBody fileBody = new FileBody(mFile); 
      multipartEntity.addPart("userfile", fileBody); 
     } 

     try { 
      multipartEntity.addPart("uid", new StringBody(uid)); 
      multipartEntity.addPart("type", new StringBody(mFile == null ? "1" : "2")); 
      multipartEntity.addPart("category", new StringBody(String.valueOf(mCategoryId + 1))); 
      multipartEntity.addPart("text", new StringBody(URLEncoder.encode(text, "UTF-8"))); 

     } catch (UnsupportedEncodingException e) { 
     } 

     final HttpParams httpParameters = new BasicHttpParams(); 
     HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); 
     HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8); 

     final HttpPost httpPost = new HttpPost("http://site.ru/add.php"); 
     httpPost.setEntity(multipartEntity); 

     final HttpClient httpClient = new DefaultHttpClient(httpParameters); 

     new AsyncTask<Void, Void, Void>() { 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 

       Toast.makeText(getContext(), "Ваш вопрос отправлен, ждите ответа", Toast.LENGTH_LONG).show(); 
      } 

      @Override 
      protected Void doInBackground(Void... voids) { 
       try { 
        final HttpResponse httpResponse = httpClient.execute(httpPost); 
        final int code = httpResponse.getStatusLine().getStatusCode(); 
        final String response = EntityUtils.toString(httpResponse.getEntity()); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

       return null; 
      } 

     }.execute(); 
    } 
+1

您是否尝试过在StringBody对象上设置编码?通过使用StringBody(字符串文本,字符集字符集)而不是 – Joey 2013-04-06 17:14:41

+0

它的工作原理!请添加它像一个答案:) – 2013-04-06 19:49:49

这里的正确答案(按评论:))

尝试直接设置StringBody对象的编码。

通过使用StringBody(String text, Charset charset)代替

如果不设置该编码,US-ASCII charset使用,这是不是你想要的。

JavaDoc for Stringbody constructor