Skip to content

Instantly share code, notes, and snippets.

@amitaymolko
Last active August 15, 2020 01:53
Show Gist options
  • Save amitaymolko/9180696181ca3f4af908 to your computer and use it in GitHub Desktop.
Save amitaymolko/9180696181ca3f4af908 to your computer and use it in GitHub Desktop.
Simple HttpURLConnection wrapper class
package com.amitaymolko.network;
import java.util.HashMap;
/**
* Created by amitaymolko on 2/16/16.
*/
public class HttpRequest {
public interface RequestCallback {
void onResponse(HttpResponse r);
}
public enum Method {
GET,
POST,
UPDATE,
DELETE
}
private Method method;
private String URL;
private HashMap<String, String> headers;
private String postData;
private RequestCallback callback;
public HttpRequest(Method method, String URL) {
this.method = method;
this.URL = URL;
}
public HttpRequest(Method method, String URL, String postData) {
this.method = method;
this.URL = URL;
this.postData = postData;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public String getMethodString() {
return method.toString();
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public HashMap<String, String> getHeaders() {
return headers;
}
public void setHeaders(HashMap<String, String> headers) {
this.headers = headers;
}
public String getPostData() {
return postData;
}
public void setPostData(String postData) {
this.postData = postData;
}
public RequestCallback getCallback() {
return callback;
}
public void setCallback(RequestCallback callback) {
this.callback = callback;
}
}
package com.amitaymolko.network;
/**
* Created by amitaymolko on 2/16/16.
*/
public class HttpResponse {
private int responseCode;
private String response;
private HttpRequest.RequestCallback callback;
public HttpResponse(int responseCode, String response, HttpRequest.RequestCallback callback) {
this.responseCode = responseCode;
this.response = response;
this.callback = callback;
}
public HttpResponse() {
}
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public HttpRequest.RequestCallback getCallback() {
return callback;
}
public void setCallback(HttpRequest.RequestCallback callback) {
this.callback = callback;
}
}
package com.amitaymolko.network;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by amitaymolko on 2/16/16.
*/
public class HttpTask extends AsyncTask<HttpRequest, String, HttpResponse> {
@Override
protected HttpResponse doInBackground(HttpRequest... params) {
URL url;
HttpURLConnection urlConnection = null;
HttpResponse response = new HttpResponse();
try {
HttpRequest request = params[0];
if (request == null || request.getURL() == null || request.getMethod() == null) {
Log.e("HttpTask", "BAD HttpRequest");
throw new Exception();
}
url = new URL(request.getURL());
urlConnection = (HttpURLConnection) url.openConnection();
Log.v("HttpTask", request.getMethodString());
urlConnection.setRequestMethod(request.getMethodString());
if (request.getHeaders() != null) {
for (HashMap.Entry<String, String> pair : request.getHeaders().entrySet()) {
urlConnection.setRequestProperty(pair.getKey(), pair.getValue());
}
}
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
if (request.getPostData() != null) {
urlConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream( urlConnection.getOutputStream());
byte[] postData = request.getPostData().getBytes();
wr.write( postData );
}
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
String responseString;
if(responseCode == HttpsURLConnection.HTTP_OK){
responseString = readStream(urlConnection.getInputStream());
}else{
responseString = readStream(urlConnection.getErrorStream());
}
Log.v("HttpTask", "Response code:"+ responseCode);
Log.v("HttpTask", responseString);
response = new HttpResponse(responseCode, responseString, request.getCallback());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
@Override
protected void onPostExecute(HttpResponse response) {
super.onPostExecute(response);
response.getCallback().onResponse(response);
}
}
package com.amitaymolko.network;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
/**
* Created by amitaymolko on 2/19/16.
*/
public class JsonAPI {
public interface JsonCallback {
void onResponse(int statusCode, JSONObject json);
}
private static JsonAPI ourInstance = new JsonAPI();
private HashMap<String, String> headers = new HashMap<>();
public static JsonAPI getInstance() {
return ourInstance;
}
private JsonAPI() {
headers.put("Content-Type","application/json");
headers.put("Accept","application/json");
}
public void addHeader(String name, String value) {
headers.put(name, value);
}
public void removeHeader(String name) {
headers.remove(name);
}
public void get(String url, final JsonCallback callback) {
HttpRequest r = new HttpRequest(HttpRequest.Method.GET, url);
r.setHeaders(headers);
r.setCallback(callbackForJsonCallback(callback));
new HttpTask().execute(r);
}
public void post(String url, JSONObject postData, JsonCallback callback) {
HttpRequest r = new HttpRequest(HttpRequest.Method.POST, url);
r.setHeaders(headers);
r.setCallback(callbackForJsonCallback(callback));
r.setPostData(postData.toString());
new HttpTask().execute(r);
}
private HttpRequest.RequestCallback callbackForJsonCallback(final JsonCallback jsonCallback) {
return new HttpRequest.RequestCallback() {
@Override
public void onResponse(HttpResponse r) {
JSONObject json = null;
try {
json = new JSONObject(r.getResponse());
} catch (JSONException e) {
e.printStackTrace();
}
jsonCallback.onResponse(r.getResponseCode(), json);
}
};
}
}
String url = "http://37.139.3.222/login";
JSONObject json = new JSONObject();
try {
json.put("email", emailEditText.getText().toString());
json.put("password", passwordEditText.getText().toString());
JsonAPI.getInstance().post(url, json, new JsonAPI.JsonCallback() {
@Override
public void onResponse(int statusCode, JSONObject json) {
if (statusCode == 200) {
String token = null;
try {
token = json.getString("token");
JsonAPI.getInstance().addHeader("Token", token);
LoginActivity.this.finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
@rizesky
Copy link

rizesky commented Apr 30, 2020

what happen if reponse code 400 or above? i didnt see you read input in error stream of the request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment