android - 使用 JSON 将数据发送到 Android 中的服务器

标签 android json

我想将数据从 Android 应用程序发送到远程服务器。我尝试将数据作为样本发送到服务器,但它正在工作。我正在下面上传我的代码。我不确定,但可能是我的数据发送格式错误。

链接需要显示成功消息。不幸的是它没有显示任何变化。

public void postData() throws JSONException {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://192.168.1.145/tracker/index.php/json/add_task");
    JSONObject json = new JSONObject();

    try {
        // JSON data:
        json.put("task_title", "Fahmi Rahman");
        json.put("task_details", "sysdev");

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        HttpResponse response = httpclient.execute(httppost);

        // for JSON:
        if(response != null)
        {
            InputStream is = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //text = sb.toString();
        }

        //tv.setText(text);

    }catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

我需要发送这个格式的数据

{"task":{
            "task_title":"All json formate",
            "task_details":"View All task list, View task list by user id, Add new task"}}

最佳答案

JsonObject 格式:

分配新的内部 JsonObject

JSONObject jInnerObject = new JSONObject();

在内部 JsonObject 中插入键和值

jInnerObject.put("task_title", "Fahmi Rahman");
jInnerObject.put("task_details", "sysdev");

分配新的外部 JsonObject

JSONObject jOuterObject = new JSONObject();

在外部对象中插入带有键的内部对象

jOuterObject.put("task", jInnerObject);
Log.i("JSonServerObject", jOuterObject.toString());

完成

关于android - 使用 JSON 将数据发送到 Android 中的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097004/

相关文章:

python - Scrapy 使用错误的编码,从网页向 JSON 添加额外的 html 标签

java - 获取 java.lang.SecurityException : Unsupported path. 但我正在请求权限

android - Activity 等待 Intent

android - 使用 LoganSquare 进行 JSON 解析

json - Freebase:使用 "namespace-prefix key"Json 对象

Javascript 解析嵌套的 JSON 对象

json - 如何使用 @JsonTypeInfo 注解的 defaultImpl 属性?

android - 在 xamarin 中关闭应用程序时接收推送通知

java - Android OnPreferenceClickListener

java - Json 到 Java 对象的转换 - Jackson 失败