blog

Home / DeveloperSection / Blogs / How to send JSON data to server with http post request

How to send JSON data to server with http post request

Manoj Pandey5211 15-Sep-2015

JSON stands for JavaScript Object Notation. It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.

JSON format
{
    "Student": [
        {
                "id": "std101",
                "name": "Zack Desouja",
                "phone": ": "+91 0000000000"
        },
        {
                "id": "std102",
                "name": "Johnny Depp",
                "phone": "mobile": "+91 0000000000"
        }
       
  ]
}

Here I am creating a sample for send JSON data to server and get response from server.

1.     Add below method in your activity.

      public String postDataToServer(String id,String name,String phone) {
          String sResponse = "";
          try {
 
// create JSONObj object and add the parameters
 
    JSONObject jsonObj = new JSONObject();
             
 
if (android.os.Build.VERSION.SDK_INT > 9) {
                  StrictMode.ThreadPolicy policy = new                           StrictMode.ThreadPolicy.Builder().permitAll().build();
 
        StrictMode.setThreadPolicy(policy);
 
          }
 
           //Add parameter in json
              jsonObj.put("Id", id);
              jsonObj.put("SName", name);
              jsonObj.put("phone", phone);
             
          // create the POST object and add set url
              HttpPost httpPost = new HttpPost(
                        " your server url”
              StringEntity entity = new StringEntity(jsonObj.toString(),
                        HTTP.UTF_8);
              entity.setContentType("application/json");
              httpPost.setEntity(entity);
              HttpClient client = new DefaultHttpClient();
              HttpResponse response = client.execute(httpPost);
 
   // get response code from server
   int responsecode =response.getStatusLine().getStatusCode();
               
    // get response String from server
 
    StringBuilder builder = new StringBuilder();
    BufferedReader bReader = new BufferedReader(     new InputStreamReader(response.getEntity().getContent()));
 
              String line = "";
              while ((line = bReader.readLine()) != null) {
                   builder.append(line);
              }
              sResponse = builder.toString();
          } catch (Exception ex) {
          }
          return sResponse;
     }
// Call the method for send data to server
 
   String data=postDataToServer("st101","Zack Desouja","+91 0000000000"); 


2.Add permission for internet in your manifest file

 

  <uses-permission android:name="android.permission.INTERNET" />

   


Leave Comment

Comments

Liked By