Wednesday, September 10, 2014

HttpPost Android example for spark


I have explained below how to use HttpPost in android to interact with spark cloud .

Httpost is mainly used to request the server to accept the entity enclosed in the request.
In our case we are sending  a post to spark cloud  from android app.

Below are the steps involved:


1> Create an object HttpClient : HttpClient is an interface for an HTTP client using which we can execute the HTTP request like GET ,POST,DELETE etc.


2> Create an object HttpPost: in our case we need to post to spark and hence we need to create an object of an HttpPost . Since we need to post to spark, the URL of spark along with device id and URI  is sent to the constructor.i.e  https://api.spark.io/v1/devices/deviceid/drive

where :
     https://api.spark.io/v1/device : is the host
     deviceid : unique if of your spark core
     drive : Uniform Resource Identifier

3> The parameters can be sent in the form of key value pair.

     access token is used for authentication and the value as to be sent in the form of string
     i.e    Key : access_token  Value :access token value.
             Key direction Value : 1 .The data are the values which is sent to spark cloud. This data has to                                                       be in String format for spark.

           

4> Now that we have mentioned the URL,URI,access token and value we can execute the post request using execute method of HttpClient created in step1.

5> The response is collected in a BufferReader and is printed to logcat.


  Important Note : Important Note : Network related operations are not recommended to run on main  thread from Honey comb and above version of sdk .If done, we do get a  NetworkOnMainThreadEXception.To avoid this you will need to run a background process or use AsyncTask to perform your network transaction on a background thread.


The below code was only for test purpose and hence i am running the network operation on main thread and to avoid the exception i am modifying StrictMode Policy which is not recommended.

Using StrictMode.ThreadPolicy.Builder, you can create your own StrictMode.ThreadPolicy, to permit or apply penalty to detected problems: 

.


Code Snippet:

 
           public class MainActivity extends Activity {
                   String TAG ="deepa";
BufferedReader in=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
//Create an object of HttpClient
                  HttpClient httpclient = new DefaultHttpClient();

//Create an object of Httppost
                  HttpPost httppost = new HttpPost("https://api.spark.io/v1/devices/deviceid/drive");
    
try {
                       // Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                      nameValuePairs.add(new BasicNameValuePair("access_token", "access_token_value"));
                      nameValuePairs.add(new BasicNameValuePair("direction", "1"));

                      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                     // Execute HTTP Post Request
                     HttpResponse response = httpclient.execute(httppost);
         in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
               }
catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
              } 
catch (IOException e) {
                    // TODO Auto-generated catch block
              }
   
// response collected in buffer and print in logcat
String s = null;

try {   
Log.d(TAG, "aaaaaaaaaa");
while ((s=in.readLine())!=null){
Log.d(TAG,s);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        } 
}

No comments:

Post a Comment