微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android post提交json数据

在Android应用程序中,我们有时需要将一些数据发送到服务器。在这种情况下,我们可以使用POST方法将JSON数据发送到服务器。

android post提交json数据

使用POST方法发送JSON数据非常简单。我们只需要创建一个HTTPURLConnection对象并设置一些请求属性。然后将JSON数据写入输出流中并关闭连接。

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL("http://example.com/submitjson");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("Accept","application/json");

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key1","value1");
            jsonObject.put("key2","value2");

            OutputStream outputStream = connection.getoutputStream();
            outputStream.write(jsonObject.toString().getBytes());
            outputStream.flush();
            outputStream.close();

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }

            String response = stringBuilder.toString();
        } catch (Exception e) {
            e.printstacktrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printstacktrace(); 
                }
            }
        }

在上面的代码中,我们创建了一个JSONObject对象并在对象中添加一些键值对。然后在HTTPURLConnection对象的输出流中写入JSONObject的字符串表示形式。

我们还设置了Content-Type和Accept请求头属性以指示服务器我们发送了JSON数据并需要JSON响应。然后,我们使用BufferedReader读取响应,将其转换成字符串并将其存储在response变量中。

在使用POST方法将JSON数据发送到服务器时,请记住设置正确的URL,请求方法为POST,设置Content-Type和Accept请求头属性,将JSON字符串写入输出流并阅读响应。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐