Java, Spring, Spring Boot

How to leverage OkHttpClient to process Request and return Response the easy way?

class YourService
{
    private static final Logger log = LoggerFactory.getLogger(YourService.class);

    private final OkHttpClient  okHttpClient;
    private final ObjectWriter  objectWriter;
    private final String        baseUrl;

    YourService(OkHttpClient okHttpClient, ObjectMapper objectMapper,
        YourHttpRequestProperties yourHttpRequestProperties)
    {
        Assert.notNull(okHttpClient, "OkHttpClient must not be null");
        this.okHttpClient = okHttpClient;

        this.objectWriter = objectMapper.writer();

      //For Http Properties you can use :  
      // @ConfigurationProperties("http") @Validated on your class
      //and wire it through properties file such as yml
        Assert.hasText(yourHttpRequestProperties.getBaseUrl(), "BaseUrl must not be blank");
        this.baseUrl = yourHttpRequestProperties.getBaseUrl();
    }

    void update(YourRequest yourRequest)
    {
        log.debug("Processing request: {}", yourRequest);

        try
        {
            String json = objectWriter.writeValueAsString(yourRequest);
            String url = baseUrl
                + "/v1/some-request";
            Request request = new Request.Builder().url(url)
                .post(RequestBody.create(
                    MediaType.parse(org.springframework.http.MediaType.APPLICATION_JSON_VALUE),
                    json))
                .build();
            try (Response response = okHttpClient.newCall(yourRequest).execute())
            {
                if (response.isSuccessful())
                {
              //Do your thing
                }
                else
                {
                    //Something
                }
            }
        }
        catch (IOException e)
        {
        //Do your thing
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *