如何发布到Json服务器Db特定格式并在android中获取响应

时间:2015-02-10 11:00:32

标签: java android xml

我需要以特定格式发布数据,这是我的格式

 {
        "Authentication": {
          "Username": "*****",
          "Password": "****"
        },
      "File": {
        "Orders": [{
               "Status":"",

            }]
      },
       "OrderID":16,
          "RequestType": 6
      }

如何以这种格式发布数据并获得响应。我试过这种方式

 HttpClient httpClient = new DefaultHttpClient();
                        JSONObject object = new JSONObject();
                        object.put("Username", "******");
                        object.put("Password", "*******");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("Authentication", object);
                        jsonObject.put("OrderID", data);
                        jsonObject.put("RequestType", 6);
                        HttpPost postMethod = new HttpPost("@@@@@@@@@@@@@");
                        postMethod.setEntity(new StringEntity(jsonObject.toString()));
                        postMethod.setHeader("Accept", "application/json");
                        postMethod.setHeader("Content-type", "application/json");
                        HttpResponse response = httpClient.execute(postMethod);
                     entity = response.getEntity();
                    response_value = EntityUtils.toString(entity).toString();
                       Log.e(TAG, response_value);

我不知道如何添加文件对象,如果你有任何想法帮助我

2 个答案:

答案 0 :(得分:0)

您只需将JSON字符串发布到服务器并指定正确的标题

application/json

服务器应以与发送时相同的格式接收json的格式。

答案 1 :(得分:0)

使用toString()将您的json对象转换为String。

示例:

                String jsonObjString = jsonObject.toString();

                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://thisisasampleurl.com");
                HttpEntity entity = new ByteArrayEntity(jsonObjectString
                        .getBytes("UTF-8"));
                post.setEntity(entity);
                HttpResponse response = client.execute(post);
                String responseString = EntityUtils.toString(response
                        .getEntity());

您的代码中已包含所需的标头。