Search This Blog

Showing posts with label HttpClient. Show all posts
Showing posts with label HttpClient. Show all posts

Sunday, March 3, 2013

Calling the web-service in android with POST and GET method

Hello guys Here i am posting the method of calling the webservice in android using POST and GET method.


public class RestClient {

   private ArrayList <NameValuePair> params;
   private ArrayList <NameValuePair> headers;

   private String url;

   private int responseCode;
   private String message;

   private String response;

   public String getResponse() {
       return response;
   }

   public String getErrorMessage() {
       return message;
   }

   public int getResponseCode() {
       return responseCode;
   }

   public RestClient(String url)
   {
       this.url = url;
       params = new ArrayList<NameValuePair>();
       headers = new ArrayList<NameValuePair>();
   }

   public void AddParam(String name, String value)
   {
       params.add(new BasicNameValuePair(name, value));
   }

   public void AddHeader(String name, String value)
   {
       headers.add(new BasicNameValuePair(name, value));
   }

   public void Execute(RequestMethod method) throws Exception
   {
       switch(method) {
           case GET:
           {
               //add parameters
               String combinedParams = "";
               if(!params.isEmpty()){
                   combinedParams += "?";
                   for(NameValuePair p : params)
                   {
                       String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),”UTF-8″);
                       if(combinedParams.length() > 1)
                       {
                           combinedParams  +=  "&" + paramString;
                       }
                       else
                       {
                           combinedParams += paramString;
                       }
                   }
               }

               HttpGet request = new HttpGet(url + combinedParams);

               //add headers
               for(NameValuePair h : headers)
               {
                   request.addHeader(h.getName(), h.getValue());
               }

               executeRequest(request, url);
               break;
           }
           case POST:
           {
               HttpPost request = new HttpPost(url);

               //add headers
               for(NameValuePair h : headers)
               {
                   request.addHeader(h.getName(), h.getValue());
               }

               if(!params.isEmpty()){
                   request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
               }

               executeRequest(request, url);
               break;
           }
       }
   }

   private void executeRequest(HttpUriRequest request, String url)
   {
       HttpClient client = new DefaultHttpClient();

       HttpResponse httpResponse;

       try {
           httpResponse = client.execute(request);
           responseCode = httpResponse.getStatusLine().getStatusCode();
           message = httpResponse.getStatusLine().getReasonPhrase();

           HttpEntity entity = httpResponse.getEntity();

           if (entity != null) {

               InputStream instream = entity.getContent();
               response = convertStreamToString(instream);

               // Closing the input stream will trigger connection release
               instream.close();
           }

       } catch (ClientProtocolException e)  {
           client.getConnectionManager().shutdown();
           e.printStackTrace();
       } catch (IOException e) {
           client.getConnectionManager().shutdown();
           e.printStackTrace();
       }
   }

   private static 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) {
           e.printStackTrace();
       } finally {
           try {
               is.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return sb.toString();
   }
}

Now here is the calling example of the method.

RestClient client = new RestClient(URL of the webservice); 
client.AddParam("param1", "String of param1"); 
client.AddParam("param2", "String of param2"); 
client.AddParam("Email", email); 
client.AddParam("Passwd", passcode); 
          try { 
                   client.Execute(RequestMethod.POST);  //  OR GET 
              }   
            catch (Exception e) {  
                  e.printStackTrace(); 
            }
 String response = client.getResponse();

Sunday, December 30, 2012

Calling the PHP web service in android and fetch the result in Android

Suppose the url of the php webservice is as follow :

http://XX.XX.XXX.XX/~serverji/home_expanditure/gethistory.php?uid=4&month=10&year=2012

XX.XX.XXX.XX stands for the server IP.

And the response from the this url is like this :

{"date":["2012-10-13","2012-10-11","2012-10-08"],"category":["The Food Expense","rent","Communication costs"],"description":["nasto","google","fii"],"expenditure":["40","100","123"]}

Then we have to go for this kind of requesting to the url :


public class HistoryDto {
  String date;
  String category;
  String descri;
  float expe;
}


static String url = "http://XX.XX.XX.XXX/~serverji/home_expanditure/";


public static ArrayList<HistoryDto> gethistory(int month, String year) {
String result = "";
InputStream is = null;
ArrayList<HistoryDto> hisList = new ArrayList<HistoryDto>();

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("uid", Myapplication
.getuserID()));
nameValuePairs.add(new BasicNameValuePair("month", "" + month));
nameValuePairs.add(new BasicNameValuePair("year", year));

try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "gethistory.php?");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString().trim();

} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

try {
JSONObject jObj = new JSONObject(result);
JSONArray JArray_date = jObj.getJSONArray("date");
JSONArray JArray_cat = jObj.getJSONArray("category");
JSONArray JArray_dis = jObj.getJSONArray("description");
JSONArray JArray_exp = jObj.getJSONArray("expenditure");
for (int i = 0; i < JArray_date.length(); i++) {
HistoryDto dto = new HistoryDto();
dto.date = JArray_date.getString(i);
dto.category = JArray_cat.getString(i);
dto.descri = JArray_dis.getString(i);
dto.expe = (float) JArray_exp.getDouble(i);

hisList.add(dto);
}

} catch (JSONException e) {
e.printStackTrace();
}
return hisList;
}



This is how we got the result to the ArrayList and populate in the android Activities.