使用网络连接发送UTF8字符集

时间:2012-09-03 12:38:16

标签: android ios

我正在尝试发送Android和Android的通知iOS使用非拉丁字符集。

我注意到当我使用非拉丁字符集从Android向iOS发送消息时,iPhone上显示的消息为“????”,因为iOS和Android的Java服务器端是相同的,我假设问题是如何我从Android手机发送请求,从iOS到iOS的通知消息正常。

下面是我用来打开网络连接并发送请求的代码,请告诉我是否正常。

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);
            }

1 个答案:

答案 0 :(得分:2)

检查以下代码对我有用,我也有同样的问题, 从服务器获取数据,

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;
希望它可以帮助你。