Skip to content

Instantly share code, notes, and snippets.

@ahouck
Created February 8, 2015 03:09
Show Gist options
  • Save ahouck/c7274ba28c5a1bcde188 to your computer and use it in GitHub Desktop.
Save ahouck/c7274ba28c5a1bcde188 to your computer and use it in GitHub Desktop.
Generic function to create HTTP Request for consuming REST interface using Java and Spring
//Utility for sending a HTTP request to an API interface regardless of parameters.
//Used this in a situation where a collection of different requests needed to be made and their result captured.
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.codehaus.jackson.map.ObjectMapper; //Can be used to map result to POJO
import org.json.JSONObject;
public void doRequest(ApiCall apiCall){
//ApiCall is just a custom wrapper class to hold all parameters for a specific API transaction that needs to occur.
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(apiCall.getBodyParameters());
ResponseEntity<JSONObject> x = restTemplate.exchange(apiCall.getURL(), apiCall.getHttpMethod(),httpEntity, JSONObject.class);
return x.getBody();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment