Last active
April 12, 2018 07:25
-
-
Save gvsharma/76c1a9a45bb7b660d3a8 to your computer and use it in GitHub Desktop.
android JSON service Handler
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