Skip to content

Instantly share code, notes, and snippets.

@hoffrocket
Created September 4, 2010 06:29
Show Gist options
  • Save hoffrocket/564962 to your computer and use it in GitHub Desktop.
Save hoffrocket/564962 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class FS {
private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static final String UTF_8 = "UTF-8";
private final String usernamePasswordEncoded;
private final String userAgent;
public FS(String username, String password, String userAgent) {
this.usernamePasswordEncoded = base64encode(username + ":" + password);
this.userAgent = userAgent;
}
public String checkin(String name, String latitude, String longitude) {
return post("checkin", "venue", name, "geolat", latitude, "geolong", longitude);
}
public String history() {
return get("history");
}
public String get(String endpoint, String... params) {
try {
String paramString = getParamString(params);
String baseUrl = getEndpointUrl(endpoint);
URL url = new URL(params.length > 0 ? baseUrl + "?" + paramString : baseUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
addAuth(conn);
return execute(conn);
} catch (Exception e) {
throw wrapException(e);
}
}
public String post(String endpoint, String... params) {
try {
URL url = new URL(getEndpointUrl(endpoint));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String paramString = getParamString(params);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
addAuth(conn);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.getOutputStream().write(paramString.getBytes(UTF_8));
return execute(conn);
} catch (Exception e) {
throw wrapException(e);
}
}
private RuntimeException wrapException(Exception e) {
return e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e);
}
private String urlEncode(String name) throws UnsupportedEncodingException {
return URLEncoder.encode(name, UTF_8);
}
private String readStream(InputStream is) throws IOException {
final char[] buffer = new char[0x1000];
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(is, UTF_8);
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read>0) {
out.append(buffer, 0, read);
}
} while (read>=0);
return out.toString();
}
private String getEndpointUrl(String endpoint) {
return "https://api.foursquare.com/v1/" + endpoint + ".json";
}
private String getParamString(String... params) throws UnsupportedEncodingException {
if (params.length % 2 != 0) {
throw new RuntimeException("unmatched params");
}
StringBuilder paramBuilder = new StringBuilder();
for (int i = 0; i < params.length; i += 2) {
paramBuilder.append(params[i]).append('=').append(urlEncode(params[i + 1]));
if (i < params.length - 2) {
paramBuilder.append('&');
}
}
return paramBuilder.toString();
}
private String execute(HttpURLConnection conn) throws IOException, Exception {
try {
return readStream(conn.getInputStream());
} catch (Exception e) {
String message = conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + readStream(conn.getErrorStream());
throw new RuntimeException(message, e);
}
}
private void addAuth(HttpURLConnection conn) {
conn.setRequestProperty("Authorization", "Basic " + usernamePasswordEncoded);
conn.setRequestProperty("User-Agent", userAgent);
}
public String base64encode(String string) {
StringBuilder encoded = new StringBuilder();
byte[] stringArray;
try {
stringArray = string.getBytes(UTF_8);
} catch (Exception ignored) {
throw wrapException(ignored);
}
// determine how many padding bytes to add to the output
int paddingCount = 3 - (stringArray.length % 3);
// add any necessary padding to the input
byte[] zeroPadded = new byte[stringArray.length + paddingCount];
System.arraycopy(stringArray, 0, zeroPadded, 0, stringArray.length);
// process 3 bytes at a time, churning out 4 output bytes
for (int i = 0; i < zeroPadded.length; i += 3) {
int j = ((zeroPadded[i] & 0xff) << 16) + ((zeroPadded[i + 1] & 0xff) << 8) + (zeroPadded[i + 2] & 0xff);
encoded.append(base64code.charAt((j >> 18) & 0x3f))
.append(base64code.charAt((j >> 12) & 0x3f))
.append(base64code.charAt((j >> 6) & 0x3f))
.append(base64code.charAt(j & 0x3f));
}
return encoded.substring(0, encoded.length() - paddingCount) + "==".substring(0, paddingCount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment