Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Android ServiceHandler using HttpURLConnection
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public final static int PUT = 3;
public final static int DELETE = 4;
public final static int PATCH = 5;
public static int STATUS_CODE = 0;
Activity mActivity;
StringBuilder sbResponse;
public ServiceHandler() {
}
public String makeServiceCall(String stringUrl, int method, String urlParameters, Activity activity,
boolean isJsonRequest) {
this.mActivity = activity;
HttpURLConnection httpURLConnection = null;
try {
if (method == GET) {
if (urlParameters != null) {
stringUrl = stringUrl + "?" + urlParameters;
}
URL url = new URL(stringUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setConnectTimeout(0);
httpURLConnection.setReadTimeout(0);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(false);
httpURLConnection.connect();
} else if (method == POST) {
URL url = new URL(stringUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setConnectTimeout(0);
httpURLConnection.setReadTimeout(0);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
if (urlParameters != null) {
if (isJsonRequest) {
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
} else {
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
}
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(urlParameters);
writer.flush();
writer.close();
os.close();
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
sbResponse = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sbResponse.append(line + "\n");
}
br.close();
STATUS_CODE = httpURLConnection.getResponseCode();
} catch (Exception ex) {
ex.printStackTrace();
try {
STATUS_CODE = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
}
httpURLConnection.disconnect();
return sbResponse.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment