Skip to content

Instantly share code, notes, and snippets.

@beradrian
Last active September 10, 2015 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beradrian/a2e478d3ae84d8f7e451 to your computer and use it in GitHub Desktop.
Save beradrian/a2e478d3ae84d8f7e451 to your computer and use it in GitHub Desktop.
Paypal API call with HttpClient
private static String paypalApiUrl = "https://api-3t.sandbox.paypal.com/nvp"; // remove sandbox. for production environment
private static NumberFormat paypalNumberFormat = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
public Map<String, String> paypalApi(Map<String, Object> params) throws ClientProtocolException, IOException {
HttpClient client = httpClientBuilder.build();
HttpPost post = new HttpPost(paypalApiUrl);
List<NameValuePair> nvpParams = new ArrayList<NameValuePair>();
for (Map.Entry<String, ?> e : params.entrySet()) {
nvpParams.add(new BasicNameValuePair(e.getKey(), e.getValue() instanceof Number
? paypalNumberFormat.format(e.getKey()) : e.getValue().toString()));
}
post.setEntity(new UrlEncodedFormEntity(nvpParams));
HttpResponse response = client.execute(post);
return parseResponse(response);
}
private String getResponseContent(HttpResponse response) throws IOException, IllegalStateException {
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String result = "";
String line = null;
while ((line = br.readLine()) != null) {
result += line;
}
return result;
}
private Map<String, String> parseResponse(HttpResponse response) throws IllegalStateException, IOException {
Map<String, String> map = new HashMap<String, String>();
for (NameValuePair nvp : URLEncodedUtils.parse(getResponseContent(response), Charset.forName("UTF-8"))) {
map.put(nvp.getName(), nvp.getValue());
}
return map;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment