首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过HTTP post从JSON中的Android到Python Flask的UTF-8编码字符串

通过HTTP post从JSON中的Android到Python Flask的UTF-8编码字符串
EN

Stack Overflow用户
提问于 2017-11-30 03:38:17
回答 0查看 368关注 0票数 0

我对此有点一无所知。

我尝试从Android客户端向Python Flask服务器发送一个JSON对象。我通过以下方式发送:

代码语言:javascript
复制
System.out.println("Building the http request");
            URL url = new URL(getString(R.string.home_server_url_send_records));
            SendTracksObject sendTracksObject = buildRecordsJson();
            JSONArray listOfRecords = sendTracksObject.listOfRecordsJsonArray;
            JSONObject sendToServerObject = new JSONObject();
            sendToServerObject.put("Track_History", listOfRecords);

            System.out.println("Sending: " + sendToServerObject.toString());
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(sendToServerObject.toString());
            String prettyJsonString = gson.toJson(je);
            System.out.println(prettyJsonString);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.connect();

            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
            os.writeBytes(sendToServerObject.toString());

            os.flush();
            os.close();

            int responseCode = conn.getResponseCode();
            String responseMessage = conn.getResponseMessage();

            System.out.println(responseCode + ": " + responseMessage);
            conn.disconnect;

这对我试图发送的大多数东西都有效,但是一旦有一个不是ASCII的字符出现在其中,比如é或§,在服务器尝试破译其中的内容之前,我就得到了一个400错误。我想这是因为编码扰乱了请求的结构,而Flask不知道如何解释结果。有趣的是,当我使用PostMan发送完全相同的请求时,它可以正常工作。

如何确保我尝试发送的字符串的编码不会与Flask打乱?

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47560489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档