Shall we make a bean and Autowire OkHttpClient

Viewed 2227
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "q=609&client=122&layer=explore&key=w3S4BEmDKd8Q3VCCO2OZTnI8sAQxIFwA&name=utkarsh%20sharma&password=utk&phone=1111111112");
Request request = new Request.Builder()
  .url("http://explore-uat.mapmyindia.in/explore-api/v1.3/")
  .post(body)
  .addHeader("Content-Type", "application/x-www-form-urlencoded")
  .addHeader("Cache-Control", "no-cache")
  .addHeader("Postman-Token", "44666246-b697-488f-9410-df09f7faa53a")
  .build();

Response response = client.newCall(request).execute();

I'am using this code to make a post request to API. I use this many times in my class. Is it possible to make a bean of OKhttpClient and autowire in my class

Please reply!!Thnx in advance

3 Answers

You could do it by declaring a bean somewhere in your configuration:

@Configuration
public class HttpClientConfiguration {

    @Bean
    public OkHttpClient httpClient() {
        return new OkHttpClient();
    }
}

Also, if not declared otherwise, every spring bean is by default a singleton: https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Regarding the initial question. I think you should declare it as a spring bean. It should ease testing.

I would declare it as Spring bean, since that makes it much easier for testing compared to a Singleton solution. However, since you are using Spring boot, you could also just use RestTemplate, as described here: https://spring.io/guides/gs/consuming-rest/

A singleton as defined below should be sufficient:

public class OkHttpFactory {

    private static OkHttpClient client = new OkHttpClient();

    public OkHttpClient getClient() {
        return client;
    }

}
Related