带有UTF8文本的POST是ASCII

时间:2013-04-06 17:08:12

标签: android post utf-8

我用这段代码打了4个小时,也许我做错了。 “text”像“????”一样来到服务器

我用:

检查了日志
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 个答案:

答案 0 :(得分:1)

这里是正确答案(根据评论:))

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

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

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

JavaDoc for Stringbody constructor

相关问题