Skip to content

Instantly share code, notes, and snippets.

@ingyesid
Last active December 17, 2015 14:29
Show Gist options
  • Save ingyesid/5624933 to your computer and use it in GitHub Desktop.
Save ingyesid/5624933 to your computer and use it in GitHub Desktop.
method for make http request
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws IOException {
AndroidHttpClient httpClient = null;
JSONObject json = null;
try {
// Building the request
httpClient = AndroidHttpClient.newInstance("android");
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),
3000);
if (method.equals("POST")) {
// request method is POST
HttpPost postRequest = new HttpPost();
URI uri = new URI(url);
postRequest.setURI(uri);
postRequest.setEntity(new UrlEncodedFormEntity(params));
// getting the response
HttpResponse httpResponse = httpClient.execute(postRequest);
final int statusCode = httpResponse.getStatusLine()
.getStatusCode();
// check the response if it's ok
if (statusCode != HttpStatus.SC_OK) {
Log.d(AppConstants.TAG, "" + httpResponse.getStatusLine());
throw new IOException("" + httpResponse.getStatusLine());
}
final HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, HTTP.UTF_8);
entity.consumeContent();
httpClient.close();
json = new JSONObject(response);
} else if (method.equals("GET")) {
// request method is GET
HttpGet getRequest = new HttpGet();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
URI uri = new URI(url);
getRequest.setURI(uri);
// getting the response
HttpResponse httpResponse = httpClient.execute(getRequest);
final int statusCode = httpResponse.getStatusLine()
.getStatusCode();
// check the response if it's ok
if (statusCode != HttpStatus.SC_OK) {
throw new IOException("" + httpResponse.getStatusLine());
}
final HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, HTTP.UTF_8);
entity.consumeContent();
httpClient.close();
json = new JSONObject(response);
}
return json;
} catch (URISyntaxException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} finally {
if (httpClient != null)
httpClient.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment