Isn't easy just to override the getMethod()
method of the HttpPost
class?
private String curl( // Return JSON String
String method, // HTTP method, for this example the method parameter should be "DELETE", but it could be PUT, POST, or GET.
String url, // Target URL
String path, // API Path
Map<String, Object> queryParams,// Query map forms URI
Map<String, Object> postParams) // Post Map serialized to JSON and is put in the header
throws Error, // when API returns an error
ConnectionClosedException // when we cannot contact the API
{
HttpClient client = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD)
.build()
).build();
HttpPost req = new HttpPost(){
@Override
public String getMethod() {
// lets override the getMethod since it is the only
// thing that differs between each of the subclasses
// of HttpEntityEnclosingRequestBase. Let's just return
// our method parameter in the curl method signature.
return method;
}
};
// set headers
req.setHeader("user-agent", "Apache");
req.setHeader("Content-type", "application/json");
req.setHeader("Accept", "application/json");
try {
// prepare base url
URIBuilder uriBuilder = new URIBuilder(url + path);
if (method.equals("GET")){
queryParams.forEach((k, v)-> uriBuilder.addParameter(k, v.toString()));
}else{
String postPramsJson = new Gson().toJson(postParams);
req.setEntity(new StringEntity(postPramsJson));
}
// set the uri
req.setURI(uriBuilder.build().normalize());
// execute the query
final HttpResponse response = client.execute(req);
//
if (response.getEntity() != null) {
if(response.getStatusLine().getStatusCode() == 200){
return EntityUtils.toString(response.getEntity());
}
logger.error("ERROR: Response code " + response.getStatusLine().getStatusCode() +
", respnse: " + EntityUtils.toString(responseEntry));
}
throw new Error("HTTP Error");
} catch (Exception e) {
logger.error("Connection error", e);
throw new ConnectionClosedException("Cannot connect to " + url);
}
}
The point is rather than having to add another class to your package... Why not just override getMethod()
in an already sub-classed object of HttpEntityEnclosingRequestBase
?