Skip to content

Instantly share code, notes, and snippets.

@sdesalas
Created November 13, 2018 21:17
Show Gist options
  • Select an option

  • Save sdesalas/6021eacb12a0dd1cdcc7bba14558a5a5 to your computer and use it in GitHub Desktop.

Select an option

Save sdesalas/6021eacb12a0dd1cdcc7bba14558a5a5 to your computer and use it in GitHub Desktop.
Android HttpHelper class extends AsyncTask<String, String, String>
package com.domain.myApp;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpHelper extends AsyncTask<String, String, String> {
public String UA = "Mozilla/5.0 (Linux; Android 6.0.1)";
public int timeout = 15 * 1000;
public String method = "GET";
public Map<String, String> headers = new HashMap<String, String>();
@Override
protected String doInBackground(String... params) {
Log.d("HttpHelper", ".doInBackground()");
String url = params[0];
Log.i("HttpHelper", "Loading " + url);
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(method);
conn.addRequestProperty("User-Agent", UA);
if (headers != null && headers.size() > 0) {
for(String key : headers.keySet()) {
conn.addRequestProperty(key, headers.get(key));
}
}
conn.setReadTimeout(timeout);
conn.connect();
JSONObject result = new JSONObject();
// Url and StatusCode
result.put("url", url);
result.put("statusCode", conn.getResponseCode());
Log.i("HttpHelper", String.format("Status %d for %s", conn.getResponseCode(), url));
/// Extract headers
JSONObject headers = new JSONObject();
Map<String, List<String>> map = conn.getHeaderFields();
if (map.size() > 0) {
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
if (key != null) {
List<String> value = entry.getValue();
headers.put(key, TextUtils.join(",", value));
}
}
}
result.put("headers", headers);
/// Extract body
InputStream in = new BufferedInputStream(conn.getInputStream());
StringBuilder response = new StringBuilder();
byte[] contents = new byte[1024];
int bytesRead;
while((bytesRead = in.read(contents)) != -1) {
response.append(new String(contents, 0, bytesRead));
}
String body = response.toString();
result.put("body", body);
try {
result.put("json", new JSONObject(body));
} catch (Exception e) {
Log.w("HttpHelper", "Unable to parse JSON body");
}
return result.toString();
} catch (Exception e) {
Log.e("HttpHelper", String.format("Unable to load url \"%s\". %s", url, e.getMessage()));
}
return null;
}
}
@sdesalas

sdesalas commented Nov 13, 2018

Copy link
Copy Markdown
Author

Usage (from within Activity code):

String url = "http://domain.com/api/thingy/123";
HttpHelper helper = new HttpHelper() {
    @Override protected void onPostExecute(String raw) {
        try {
            JSONObject result = new JSONObject(raw);
            Log.i(TAG, result);
        } catch (Exception ex) {
            Log.e(TAG, "HttpHelper.onPostExecute() " + ex.getMessage());
        }
    }
};
helper.timeout = 5 * 1000;
helper.execute(url);

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