Skip to content

Instantly share code, notes, and snippets.

@craigchristenson
Created August 1, 2012 13:11
Show Gist options
  • Save craigchristenson/3226721 to your computer and use it in GitHub Desktop.
Save craigchristenson/3226721 to your computer and use it in GitHub Desktop.
2Checkout Api Class Example
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class TwocheckoutApi {
public static JSONObject get(String url, List<NameValuePair> params, String apiusername, String apipassword) {
url = addLocationToUrl(url, params);
JSONObject mainObject = null;
try {
URI uri = new URI(url);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(apiusername, apipassword));
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json");
String response = httpclient.execute(httpget, new BasicResponseHandler());
if (response != null) {
mainObject = new JSONObject(response);
return mainObject;
}
} catch (Exception e) {
e.printStackTrace();
return mainObject;
}
return mainObject;
}
public static JSONObject post(String url, ArrayList<NameValuePair> params, String apiusername, String apipassword) {
JSONObject mainObject = null;
try {
URI uri = new URI(url);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(apiusername, apipassword));
HttpPost httppost = new HttpPost(uri);
httppost.setHeader("Accept", "application/json");
httppost.setEntity(new UrlEncodedFormEntity(params));
String response = httpclient.execute(httppost, new BasicResponseHandler());
if (response != null) {
mainObject = new JSONObject(response);
return mainObject;
}
} catch (Exception e) {
e.printStackTrace();
return mainObject;
}
return mainObject;
}
public static String addLocationToUrl(String url, List<NameValuePair> params){
if(!url.endsWith("?"))
url += "?";
String paramString = URLEncodedUtils.format(params, "utf-8");
url += paramString;
return url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment