Created
August 1, 2018 12:12
-
-
Save cliffgr/0d89a508877b772f7cefd9508711c74b to your computer and use it in GitHub Desktop.
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
package com.wappier.wappierSDK.network.networkrequest; | |
import android.content.Context; | |
import android.net.Uri; | |
import android.os.AsyncTask; | |
import android.os.Build; | |
import android.support.annotation.Nullable; | |
import android.util.Base64; | |
import android.util.Log; | |
import com.wappier.wappierSDK.Constants; | |
import com.wappier.wappierSDK.SessionHandler; | |
import com.wappier.wappierSDK.Wappier; | |
import com.wappier.wappierSDK.network.NetworkResponse; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.BufferedReader; | |
import java.io.BufferedWriter; | |
import java.io.DataOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.io.OutputStreamWriter; | |
import java.io.UnsupportedEncodingException; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import java.util.Map; | |
import javax.net.ssl.HttpsURLConnection; | |
public class NetworkRequestAsyncTask extends AsyncTask<Void, Void, Boolean> { | |
private final String LOG_TAG = NetworkRequestAsyncTask.class.getSimpleName(); | |
private String response, baseUrl, endpoint; | |
private Map<String, String> params, headers; | |
private Object object; | |
private RequestType requestType; | |
private ContentType contentType; | |
private Context context; | |
private int code; | |
private Object message; | |
private Object error; | |
private String charset = "UTF-8"; | |
private boolean decodedUrlInUTF = false; | |
private OnNetworkRequestResponseListener onNetworkRequestResponseListener; | |
NetworkRequestAsyncTask(Context context, String baseUrl, String endpoint, RequestType requestType, | |
ContentType contentType, @Nullable Map<String, String> params, | |
@Nullable Map<String, String> headers, @Nullable Object object) { | |
this.context = context; | |
this.baseUrl = baseUrl; | |
this.endpoint = endpoint; | |
this.requestType = requestType; | |
this.contentType = contentType; | |
if (params != null) | |
this.params = params; | |
if (headers != null) | |
this.headers = headers; | |
if (object != null) | |
this.object = object; | |
} | |
@Override | |
protected void onPreExecute() { | |
super.onPreExecute(); | |
} | |
@Override | |
protected Boolean doInBackground(Void... par) { | |
HttpURLConnection urlConnection = null; | |
BufferedReader reader = null; | |
response = null; | |
try { | |
urlConnection = getStructuredRequest(baseUrl, endpoint, requestType, contentType, params, headers, object); | |
assert urlConnection != null; | |
InputStream is = urlConnection.getInputStream(); | |
StringBuilder buffer = new StringBuilder(); | |
if (is == null) { | |
return null; | |
} | |
reader = new BufferedReader(new InputStreamReader(is)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
buffer.append(line).append("\n"); | |
} | |
if (buffer.length() == 0) | |
return null; | |
response = buffer.toString(); | |
return true; | |
} catch (Exception e) { | |
manageError(e, urlConnection); | |
return false; | |
} finally { | |
if (urlConnection != null) { | |
urlConnection.disconnect(); | |
} | |
if (reader != null) { | |
try { | |
reader.close(); | |
} catch (IOException e) { | |
Log.e(LOG_TAG, "Error Closing Stream", e); | |
} | |
} | |
} | |
} | |
@Override | |
protected void onPostExecute(Boolean result) { | |
NetworkResponse networkResponse = new NetworkResponse(); | |
if (result == null) { | |
networkResponse.setCode(Constants.UNKNOWN_ERROR); | |
onNetworkRequestResponseListener.onErrorResponse(networkResponse); | |
return; | |
} | |
if (result) { | |
if (onNetworkRequestResponseListener != null) { | |
networkResponse.setCode(code); | |
networkResponse.setResponse(response); | |
onNetworkRequestResponseListener.onSuccessResponse(networkResponse); | |
} | |
} else { | |
if (onNetworkRequestResponseListener != null) { | |
networkResponse.setCode(code); | |
networkResponse.setError(error); | |
onNetworkRequestResponseListener.onErrorResponse(networkResponse); | |
} | |
} | |
} | |
private HttpURLConnection getStructuredRequest(String baseUrl, String endpoint, RequestType type, | |
ContentType contentType, | |
@Nullable Map<String, String> params, | |
@Nullable Map<String, String> headers, | |
@Nullable Object object) throws Exception { | |
HttpURLConnection urlConnection = null; | |
URL url = null; | |
Uri.Builder builderPath = buildPath(baseUrl, endpoint); | |
switch (type) { | |
case GET: | |
if (params != null) { | |
for (Map.Entry<String, String> entry : params.entrySet()) { | |
if (decodedUrlInUTF) { | |
String decode = entry.getValue(); | |
decode = decode.replace(" ", "%20"); | |
builderPath.appendQueryParameter(entry.getKey(), decode); | |
} else { | |
builderPath.appendQueryParameter(entry.getKey(), entry.getValue()); | |
} | |
} | |
} | |
url = new URL(getCompletePath(builderPath.build().toString())); | |
urlConnection = openConnectWithProtocol(url); | |
urlConnection.setRequestMethod(type.name()); | |
urlConnection = setHeaders(urlConnection, headers, contentType); | |
urlConnection.connect(); | |
break; | |
case POST: | |
url = new URL(getCompletePath(builderPath.build().toString())); | |
urlConnection = openConnectWithProtocol(url); | |
urlConnection.setRequestMethod(type.name()); | |
urlConnection = setHeaders(urlConnection, headers, contentType); | |
urlConnection.setDoInput(true); | |
urlConnection.setDoOutput(true); | |
if (object != null) { // A JSON object will be send it. | |
urlConnection.connect(); | |
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream()); | |
dataOutputStream.write(object.toString().getBytes()); | |
dataOutputStream.flush(); | |
dataOutputStream.close(); | |
} else { // if there is no JSON object will create the request with encoded url params | |
Uri.Builder builder = new Uri.Builder(); | |
if (params != null) { | |
for (Map.Entry<String, String> entry : params.entrySet()) { | |
builder.appendQueryParameter(entry.getKey(), entry.getValue()); | |
} | |
String query = builder.build().getEncodedQuery(); | |
OutputStream os = urlConnection.getOutputStream(); | |
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, charset)); | |
writer.write(query); | |
writer.flush(); | |
writer.close(); | |
urlConnection.connect(); | |
} | |
} | |
break; | |
case PUT: | |
url = new URL(getCompletePath(builderPath.build().toString())); | |
urlConnection = openConnectWithProtocol(url); | |
urlConnection.setRequestMethod(type.name()); | |
urlConnection = setHeaders(urlConnection, headers, contentType); | |
urlConnection.setDoInput(true); | |
urlConnection.setDoOutput(true); | |
if (object != null) { | |
urlConnection.connect(); | |
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream()); | |
dataOutputStream.write(object.toString().getBytes()); | |
dataOutputStream.flush(); | |
dataOutputStream.close(); | |
} else { | |
Uri.Builder builder = new Uri.Builder(); | |
if (params != null) { | |
for (Map.Entry<String, String> entry : params.entrySet()) { | |
builder.appendQueryParameter(entry.getKey(), entry.getValue()); | |
} | |
String query = builder.build().getEncodedQuery(); | |
OutputStream os = urlConnection.getOutputStream(); | |
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, charset)); | |
writer.write(query); | |
writer.flush(); | |
writer.close(); | |
urlConnection.connect(); | |
} | |
} | |
break; | |
case PATCH: | |
url = new URL(getCompletePath(builderPath.build().toString())); | |
urlConnection = openConnectWithProtocol(url); | |
urlConnection.setRequestMethod(type.name()); | |
urlConnection = setHeaders(urlConnection, headers, contentType); | |
urlConnection.setDoInput(true); | |
urlConnection.setDoOutput(true); | |
if (object != null) { | |
urlConnection.connect(); | |
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream()); | |
dataOutputStream.write(object.toString().getBytes()); | |
dataOutputStream.flush(); | |
dataOutputStream.close(); | |
} else { | |
Uri.Builder builder = new Uri.Builder(); | |
if (params != null) { | |
for (Map.Entry<String, String> entry : params.entrySet()) { | |
builder.appendQueryParameter(entry.getKey(), entry.getValue()); | |
} | |
String query = builder.build().getEncodedQuery(); | |
OutputStream os = urlConnection.getOutputStream(); | |
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, charset)); | |
writer.write(query); | |
writer.flush(); | |
writer.close(); | |
urlConnection.connect(); | |
} | |
} | |
break; | |
case DELETE: | |
url = new URL(getCompletePath(builderPath.build().toString())); | |
urlConnection = openConnectWithProtocol(url); | |
urlConnection.setRequestMethod(type.name()); | |
urlConnection = setHeaders(urlConnection, headers, contentType); | |
urlConnection.setDoInput(true); | |
urlConnection.setDoOutput(true); | |
if (object != null) { | |
urlConnection.connect(); | |
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream()); | |
dataOutputStream.write(object.toString().getBytes()); | |
dataOutputStream.flush(); | |
dataOutputStream.close(); | |
} | |
break; | |
} | |
return urlConnection; | |
} | |
private String getCompletePath(String path) { | |
String decodedUrlInUTF = ""; | |
try { | |
decodedUrlInUTF = NetworkRequestAsyncTask.this.decodedUrlInUTF ? | |
java.net.URLDecoder.decode(path, charset) : path; | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
return decodedUrlInUTF; | |
} | |
private Uri.Builder buildPath(String baseUrl, String endpoint) { | |
Uri.Builder builderPath = Uri.parse("").buildUpon(); | |
if (baseUrl != null && !baseUrl.equalsIgnoreCase("")) { | |
builderPath = Uri.parse(baseUrl).buildUpon(); | |
} else { | |
Log.e(LOG_TAG, "No Base URL was set"); | |
} | |
builderPath.appendPath(endpoint); | |
return builderPath; | |
} | |
private HttpURLConnection openConnectWithProtocol(URL url) throws IOException { | |
if (url.getProtocol().equals("http")) { | |
return (HttpURLConnection) url.openConnection(); | |
} else { | |
return (HttpsURLConnection) url.openConnection(); | |
} | |
} | |
private HttpURLConnection setHeaders(HttpURLConnection urlConnection, @Nullable Map<String, String> headers, | |
ContentType contentType) { | |
if (contentType == ContentType.JSON) { | |
urlConnection.setRequestProperty("Content-Type", "application/json"); | |
urlConnection.setRequestProperty("Accept", "application/json"); | |
urlConnection.setRequestProperty("X-Wappier-App", String.format("%s/%s/%s/%s", Wappier.sPackageName, Wappier.sAppVersion, "Wappier-SDK", Wappier.sSdkVersion)); | |
urlConnection.setRequestProperty("X-Wappier-ID", Wappier.sSessionHandler.getStringPreference(SessionHandler.WAPPIER_ID)); | |
urlConnection.setRequestProperty("X-Wappier-Device", String.format("%s/%s/%s", Build.BRAND, Build.MODEL.replaceAll("\\r|\\n|\\,", ""), Build.VERSION.RELEASE)); | |
urlConnection.setRequestProperty("User-Agent", Wappier.sUserAgent); | |
urlConnection.setRequestProperty("X-Wappier-Ref", String.format("%s", Wappier.sSessionHandler.getStringPreference(SessionHandler.REFERRER, null))); | |
String basicAuth = "Basic " + new String(Base64.encode(Wappier.sSessionHandler.getStringPreference(SessionHandler.APP_TOKEN).getBytes(), Base64.DEFAULT)); | |
urlConnection.setRequestProperty("Authorization", basicAuth); | |
} else if (contentType == ContentType.XML) { | |
urlConnection.setRequestProperty("Content-Type", "application/xml"); | |
urlConnection.setRequestProperty("Accept", "application/xml"); | |
} | |
if (headers != null && urlConnection != null) { | |
for (Map.Entry<String, String> entry : headers.entrySet()) { | |
urlConnection.setRequestProperty(entry.getKey(), entry.getValue()); | |
} | |
} | |
return urlConnection; | |
} | |
private void manageError(Exception e, HttpURLConnection urlConnection) { | |
if (urlConnection != null) { | |
try { | |
code = urlConnection.getResponseCode(); | |
if (urlConnection.getErrorStream() != null) { | |
InputStream is = urlConnection.getErrorStream(); | |
StringBuilder buffer = new StringBuilder(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
buffer.append(line).append("\n"); | |
} | |
message = buffer.toString(); | |
} else { | |
message = urlConnection.getResponseMessage(); | |
} | |
error = urlConnection.getErrorStream().toString(); | |
} catch (Exception e1) { | |
e1.printStackTrace(); | |
Log.e(LOG_TAG, "Error: " + e1.getMessage()); | |
} | |
} else { | |
JSONObject object = new JSONObject(); | |
try { | |
object.put("code", "105"); | |
object.put("message", "Error: No internet connection"); | |
object.put("error", "Error: No internet connection"); | |
object.put("title", "No internet connection."); | |
object.put("description", "Houston we have a problem"); | |
} catch (JSONException e1) { | |
e1.printStackTrace(); | |
} | |
code = 105; | |
error = object.toString(); | |
} | |
} | |
void setOnNetworkRequestResponseListener(OnNetworkRequestResponseListener onNetworkRequestResponseListener) { | |
this.onNetworkRequestResponseListener = onNetworkRequestResponseListener; | |
} | |
void setDecodedUrlInUTF(boolean decodedUrlInUTF) { | |
this.decodedUrlInUTF = decodedUrlInUTF; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment