Horhe Garcia
Horhe Garcia

Reputation: 902

POST with text in UTF8 comes as ASCII

I am fighting 4 hours with this code, perhaps i'm doing something wrong. "text" comes to server like "????"

I've checked the logs with:

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

it gives me 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();
    }

Upvotes: 1

Views: 450

Answers (1)

Joey
Joey

Reputation: 1349

Here the correct answer (as per comment :) )

Try setting the encoding on the StringBody object directly.

By using StringBody(String text, Charset charset) instead

If you don't set the encoding, the US-ASCII charset is used, which is not what you wanted.

JavaDoc for Stringbody constructor

Upvotes: 1

Related Questions