在 Android 中使用 DataOutputStream 在 POST 正文中发送特殊字符 (ë ä ï)

2024-05-19

我目前正在开发一个具有大量服务器端通信的 Android 应用程序。昨天,我收到一份错误报告,称用户无法发送(简单)特殊字符,例如 ëäï。

我搜索过但没有找到任何有用的东西 可能重复(没有答案):https://stackoverflow.com/questions/12388974/android-httpurlconnection-post-special-charactes-to-rest-clint-in-android https://stackoverflow.com/questions/12388974/android-httpurlconnection-post-special-charactes-to-rest-clint-in-android

我的相关代码:

public void execute(String method) {
        HttpsURLConnection urlConnection = null;
        try {
            URL url = new URL(this.url);
            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestMethod(method);
            urlConnection.setReadTimeout(30 * 1000);
            urlConnection.setDoInput(true);

            if (secure)
                urlConnection.setRequestProperty("Authorization", "Basic " + getCredentials());

            if (body != null) {
                urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");


                urlConnection.setFixedLengthStreamingMode(body.length());
                urlConnection.setDoOutput(true);
                DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
                dos.writeBytes(body);
                dos.flush();
                dos.close();
            }

            responseCode = urlConnection.getResponseCode();
            message = urlConnection.getResponseMessage();

            InputStream in = null;

            try {
                in = new BufferedInputStream(urlConnection.getInputStream(), 2048);
            } catch (Exception e) {
                in = new BufferedInputStream(urlConnection.getErrorStream(), 2048);
            }

            if (in != null)
                response = convertStreamToString(in);

        } catch (UnknownHostException no_con) {
            responseCode = 101;
        }catch (ConnectException no_con_2){
            responseCode = 101;
        }catch(IOException io_ex){
            if(io_ex.getMessage().contains("No authentication challenges found")){
                responseCode = 401;
            }else
                responseCode = 101;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
        }
    }

body是一个字符串;-)

希望我们能一起解决这个问题

UPDATE:

Tried:


writeUTF()

需要一个能够理解修改后的 UTF-8 的服务器


byte[] buf = body.getBytes("UTF-8");
dos.write(buf, 0, buf.length);

字符串可以工作,但没有特殊字符

更新:让它与 StringEntity(* string, "UTF-8") 一起使用,然后将结果解析为 byte[] 并用 dos.write(byte[]) 写入!

--


设置 StringEntity 的编码对我来说很有效:

StringEntity entity = new StringEntity(body, "UTF-8");

在这里看到:https://stackoverflow.com/a/5819465/570168 https://stackoverflow.com/a/5819465/570168

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Android 中使用 DataOutputStream 在 POST 正文中发送特殊字符 (ë ä ï) 的相关文章

随机推荐