user836026
user836026

Reputation: 11350

sending UTF8 charset using network connection

I'm trying to send notification for both Android & iOS using non-Latin charset.

I notice when I send message from Android to iOS using non-Latin charset, message displayed on iPhone as "????", since the Java server side for iOS and Android are the same, I assume the problem is how I send the request from Android handset, notice message from iOS to iOS works fine.

below is the code that I'm using to open network connection and sending the request, please, let me know if it's OK.

byte[] bytes = body.getBytes(/*"UTF-16"*//*"ISO-8859-1"*/"UTF-8");

        HttpURLConnection conn = null;

        StringBuilder stringBuilder = new StringBuilder();

        try {

            conn = (HttpURLConnection) url.openConnection();//conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            // handle the response
            int status = conn.getResponseCode();
            if (status != 200) {
                Log.d("send message", "Coud Send Message, No Internet Connection Avilable.");
                throw new IOException("Post failed with error code " + status);
            }

            InputStream in = new BufferedInputStream(conn.getInputStream());
            // readStream(in);
            int b;
            while ((b = in.read()) != -1) {
                stringBuilder.append((char) b);
            }

Upvotes: 0

Views: 445

Answers (1)

Dhaval Parmar
Dhaval Parmar

Reputation: 18978

check below code it works for me, i have also same issue, to get Data from server,

String is = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs2,
                    HTTP.UTF_8));
            HttpResponse responce = httpclient.execute(httppost);
            HttpEntity entity = responce.getEntity();
            is = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            // TODO: handle exception
            Log.d("call http :", e.getMessage().toString());
            is = null;
        }
        return is;

hope it may help you.

Upvotes: 2

Related Questions