I am working on an HTTP Client SDK where I implemented the bridge pattern, the architecture looks like this:
The reasoning for this is that I can have multiple types of bodies and HTTP methods to implement for each type of Message, so with this I believed I would reduce the amount of classes I would create.
Something that I've noticed and has bothered me a lot is in the SMS request portion I am repeating a lot of the RestTemplate code to send the submits example:
@Override
public AdvancedSmsResponse postMessage() {
super.httpHeaders.set("Authorization", super.authorization.toBase64());
super.httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
super.httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(smsAdvanced, httpHeaders);
try{
ResponseEntity<AdvancedSmsResponse> response = super.requestRestTemplate.exchange(getUrlHost(), HttpMethod.POST, entity, AdvancedSmsResponse.class);
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String smsResponseLog = objectMapper.writeValueAsString(response.getBody());
super.LOGGER.info( "\n" + response.getStatusCode() + "\n" + smsResponseLog);
return response.getBody();
}catch (HttpStatusCodeException | JsonProcessingException e){
return null;
}
}
@Override
public Object getDeliveryReport() {
super.httpHeaders.set("Authorization", super.authorization.toBase64());
super.httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
super.httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(null, httpHeaders);
try{
ResponseEntity<AdvancedSmsResponse> response = super.requestRestTemplate.exchange(getUrlHost() + "/report", HttpMethod.GET, entity, AdvancedSmsResponse.class);
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String smsResponseLog = objectMapper.writeValueAsString(response.getBody());
super.LOGGER.info( "\n" + response.getStatusCode() + "\n" + smsResponseLog);
return response.getBody();
}catch (HttpStatusCodeException | JsonProcessingException e){
return null;
}
}
Is this implementation good? And also is there is a way to avoid so much repetition for the request execution part?
I would be tempted to extract a method that accepts the HttpEntity, the path and the HTTP method. However, I have not seen the full set of your requests. If you have a small number of things that varies, then this simple extraction might be enough to avoid the repeating code. If you have a lot of things that vary then a builder might be the way to go.