android - 如何使用 Android 通过 Request 发送 JSON 对象?

我想发送以下 JSON 文本

{"Email":"aaa@tbbb.com","Password":"123456"}

到网络服务并阅读响应。我知道如何阅读 JSON。问题是上面的 JSON 对象必须以变量名 jason 的形式发送。

我怎样才能从 android 做到这一点?创建请求对象、设置内容头等步骤有哪些?

最佳答案

如果您使用 Apache HTTP 客户端,从 Android 发送 json 对象很容易。这是有关如何执行此操作的代码示例。您应该为网络 Activity 创建一个新线程,以免锁定 UI 线程。

    protected void sendJson(final String email, final String pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(URL);
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                    createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }

您也可以使用 Google Gson发送和检索 JSON。

https://stackoverflow.com/questions/3027066/

相关文章:

json - REST API - 文件(即图像)处理 - 最佳实践

ios - 如何在 Swift 中解析来自 Alamofire API 的 JSON 响应?

javascript - 如何动态创建 JavaScript 数组(JSON 格式)?

json - 如何在结构中定义多个名称标签

javascript - 从浏览器下载 JSON 对象作为文件

javascript - 通过 JavaScript 动态创建 JSON 对象(没有连接字符串)

c# - 在 JSON.NET 中反序列化的转换接口(interface)

c# - JSON.net:如何在不使用默认构造函数的情况下反序列化?

arrays - YAML 等效于 JSON 中的对象数组

mysql - 在 MySQL 中以 JSON 格式存储数据