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

android 上传json

Android作为一款普及度极高的操作系统,其上传json数据的需求很常见。下面介绍一下如何在Android中上传json。

android 上传json

首先需要使用HttpURLConnection对象来建立与服务器的连接:

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type","application/json");
    conn.setDoOutput(true);
    conn.setDoInput(true);

接下来,需要将数据转换为json格式:

    JSONObject json = new JSONObject();
    json.put("name","android");
    json.put("version","9.0");

    String jsonStr = json.toString();

然后,将json数据写入HttpURLConnection的输出流:

    OutputStream os = conn.getoutputStream();
    os.write(jsonStr.getBytes());
    os.flush();
    os.close();

最后,发送请求并获取服务器的响应:

    int responseCode = conn.getResponseCode();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    String responseStr = response.toString();

至此,json数据上传成功,服务器也返回了成功的响应结果。

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

相关推荐