简体   繁体   中英

How to Post to Json server Db particular format and get response in android

I need to post the data in a particular format here is my format

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

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

How to post the data in this format and get the response .I tried in this way

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

I dont Know how to add the file object in that ,if you have any idea help me

You just POST the JSON string to the server and specify the correct header

application/json

The format of the json should be received by the server in the same format as it was sent.

Use toString() to convert your json object to String.

Example :

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

You already have the required headers in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM