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



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

 {
        "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);

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

您只需将JSON字符串POST到服务器并指定正确的头

application/json

json的格式应该以发送时的格式由服务器接收。

使用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());

您的代码中已经有了所需的标头。

最新更新