Created
June 16, 2015 06:32
-
-
Save muratcanbur/b7a2c1c482bfd5e16c86 to your computer and use it in GitHub Desktop.
a separate class to handle all HTTP calls. This class is responsible of making a HTTP call and getting the response.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ServiceHandler { | |
static String response = null; | |
public final static int GET = 1; | |
public final static int POST = 2; | |
public ServiceHandler() { | |
} | |
/** | |
* Making service call | |
* @url - url to make request | |
* @method - http request method | |
* */ | |
public String makeServiceCall(String url, int method) { | |
return this.makeServiceCall(url, method, null); | |
} | |
/** | |
* Making service call | |
* @url - url to make request | |
* @method - http request method | |
* @params - http request params | |
* */ | |
public String makeServiceCall(String url, int method, | |
List<NameValuePair> params) { | |
try { | |
// http client | |
DefaultHttpClient httpClient = new DefaultHttpClient(); | |
HttpEntity httpEntity = null; | |
HttpResponse httpResponse = null; | |
// Checking http request method type | |
if (method == POST) { | |
HttpPost httpPost = new HttpPost(url); | |
// adding post params | |
if (params != null) { | |
httpPost.setEntity(new UrlEncodedFormEntity(params)); | |
} | |
httpResponse = httpClient.execute(httpPost); | |
} else if (method == GET) { | |
// appending params to url | |
if (params != null) { | |
String paramString = URLEncodedUtils | |
.format(params, "utf-8"); | |
url += "?" + paramString; | |
} | |
HttpGet httpGet = new HttpGet(url); | |
httpResponse = httpClient.execute(httpGet); | |
} | |
httpEntity = httpResponse.getEntity(); | |
response = EntityUtils.toString(httpEntity); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} catch (ClientProtocolException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment