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



我正在尝试为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);
            }

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

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;

希望它能帮助你。

最新更新