how to post json data to server in android








HTTP POST permits you to send information to the server in diverse organizations, for example, XML, JSON or twofold. Obviously, the server ought to be prepared to handle information in the chose design. This article demonstrates to send JSON information from Android application to a server that can deal with it.

Objectives:

- :  How to send JSON information to the server utilizing HTTP POST?

Environment & Tools:


  • Android Developer Tools (ADT) (or Eclipse + ADT plugin)
  • AVD Nexus S Android 4.3 “emulator”
  • Min SDK 8
  • Server side service that can receive HTTP POST request with data in JSON format 

Source Code   -

public class MainActivity extends Activity{
String mainResult="";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        Person p = new Person();
        p.setClientTime("04-04-2015 12:34:22");
        p.setMethod("100");
        p.setAPIKey("5987ac798eb9c2ed5801E2E6E2pkJ8");
        p.setEmail("prabht@gmail.com");
        p.setPassword("123");
        
        new dheeraj().execute("http://dheeru-bhadoria.netne.net/test/APICloud.php", toJSon(p));
    
        //String result = POST("dheeru-bhadoria.netne.net/test/APICloud.php", toJSon(p));
        //Toast.makeText(MainActivity.this,result, 1).show();
        
    }
    
    public static String toJSon(Person person) {
        try {
          // Here we convert Java Object to JSON 
          JSONObject jsonObj = new JSONObject();

          JSONObject jsonclient = new JSONObject(); // we need another object to store the address
          jsonclient.put("ClientTime", person.getClientTime()); // Set the first name/pair 
          jsonclient.put("Method", person.getMethod());
          jsonclient.put("APIKey", person.getAPIKey());
          
          JSONObject jsonAdd = new JSONObject(); // we need another object to store the address
          jsonAdd.put("email", person.getEmail());
          jsonAdd.put("password", person.getPassword());

          // We add the object to the main object
          jsonObj.put("Data", jsonAdd);

          jsonObj.put("ConnectionData", jsonclient);
          
          // and finally we add the phone number
          // In this case we need a json array to hold the java list
       
          Log.d("Json String", jsonObj.toString());
          return jsonObj.toString();

      }
      catch(JSONException ex) {
          ex.printStackTrace();
      }

      return null;

  }
    
    public  String POST(String url,String jsonstring){
        InputStream inputStream = null;
        String result = "";
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            String json = jsonstring;
            // 3. build jsonObject
    /*        JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("ClientTime", "04-04-2015 12:34:22");
            jsonObject.accumulate("Method", "100");
            jsonObject.accumulate("APIKey", "5987ac798eb9c2ed5801E2E6E2pkJ8");
            jsonObject.accumulate("email", "prabht@gmail.com");
            jsonObject.accumulate("password", "123");*/
            
           /* JSONObject mainObj = new JSONObject();
            
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("ClientTime", "04-04-2015 12:34:22"); // Set the first name/pair 
            jsonObj.put("Method", 100);
            jsonObj.put("APIKey", "5987ac798eb9c2ed5801E2E6E2pkJ8");

            mainObj.put("ConnectionData", jsonObj);
            
            JSONObject jsonAdd = new JSONObject(); // we need another object to store the address
            jsonAdd.put("email", "prabht@gmail.com");
            jsonAdd.put("password", "123");
            

            // We add the object to the main object
            jsonObj.put("Data", jsonAdd);
            
            
            
            // 4. convert JSONObject to JSON to String
         //   json = jsonObject.toString();
            json = jsonObj.toString();
            */
            System.out.println("json======"+json);
            
            // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person); 
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content   
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
            // 10. convert inputstream to string
            if(inputStream != null)
                result = convertStreamToString(inputStream);
            else
                result = "Did not work!";
            System.out.println("result======"+result);
        } catch (Exception e) {
            //Log.d("InputStream", e.getLocalizedMessage());
            System.out.println("result======"+e.toString());
        }
        // 11. return result
        return result;
    }  
    

public String convertStreamToString(InputStream is) {
 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) {
 } finally {
   try {
     is.close();
   } catch (IOException e) {
   }
 }
 
 return sb.toString();
}
class dheeraj extends AsyncTask<String,Void, String> {

   private Exception exception;
   
  
 

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
mainResult= POST(params[0],params[1]);
Log.d("Result", mainResult);
return mainResult;
       //Toast.makeText(MainActivity.this,result, 1).show();
}
}
}


0 comments:

Post a Comment

My Instagram