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

android 发送json

Android是 目前市场占有率最高的操作系统之一。它广泛应用于各种类型的 移动设备,并具有强大的API支持一个常见的任务是从Android设备向web服务发送JSON数据。

android 发送json

在Android中,发送JSON数据需要遵循以下步骤:

1. 创建JSON对象或字符串
2. 将JSON对象或字符串放入HttpRequest实例中
3. 发送HttpRequest实例到web服务

以下是一个使用Android代码发送JSON的示例。

private void sendJsonToServer() {

    try {
        // Create a JSON object with some data
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name","John Smith");
        jsonObj.put("email","[email protected]");
        jsonObj.put("phone","1234567890");

        // Create a new HttpClient and HttpRequest instance
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://example.com/");

        // Add the JSON data to the POST request
        StringEntity se = new StringEntity(jsonObj.toString());
        httppost.setEntity(se);
        httppost.setHeader("Accept","application/json");
        httppost.setHeader("Content-type","application/json");

        // Send the POST request to the web service
        HttpResponse response = httpclient.execute(httppost);

        // Process the response
        String responseBody = EntityUtils.toString(response.getEntity());

        Log.d(TAG,"Response: " + responseBody);

    } catch (Exception e) {
        Log.e(TAG,"Error: " + e.getMessage());
    }
}

这个示例创建了一个包含“name”、“email”和“phone”的JSON对象,并将其放入HttpRequest实例中。POST请求将被发送到http://example.com/。

最后,处理响应并对结果执行适当的操作。在本示例中,响应正文被转换为字符串并记录在Android的Logcat输出中。

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

相关推荐