Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-boot gets an error when creating custom RestTemplate

I have a sendGetREST method to send some URL endpoint and get the response:

@Component
public class HttpURLCommand {
    private static Logger logger = Logger.getLogger(HttpURLCommand.class);

public String sendGetREST(String soapUrl, Object[] parameters) throws IOException{
        final String SOAP_URL = MessageFormat.format(soapUrl, parameters);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(SOAP_URL, String.class);

    logger.info("status code is: "+response.getStatusCode());
    if(response.getStatusCode().equals(HttpStatus.OK)){
        logger.info("send success");
        return response.getBody();
    }
    else {
        logger.info("send failed");
        return null;
    }

  }
}

Which is working well. However, in order to make the timeout time customizable, I have this HTTPConfiguration from this tutorial:

@Configuration
public class HTTPConfiguration {

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(clientHttpRequestFactory());
}

private ClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(60000);
    factory.setConnectTimeout(60000);
    return factory;
   }
}

So the class will be calling restTemplate like this:

@Component
 public class HttpURLCommand {
    private static Logger logger = Logger.getLogger(HttpURLCommand.class);
    @Autowired
    RestTemplate restTemplate;

public String sendGetREST(String soapUrl, Object[] parameters) throws IOException{
        final String SOAP_URL = MessageFormat.format(soapUrl, parameters);
        ResponseEntity<String> response = restTemplate.getForEntity(SOAP_URL, String.class);

    logger.info("status code is: "+response.getStatusCode());
    if(response.getStatusCode().equals(HttpStatus.OK)){
        logger.info("send success");
        return response.getBody();
    }
    else {
        logger.info("send failed");
        return null;
    }

  }
}

But unfortunately return this following error when builds the spring-boot app:

Caused by: java.lang.NoClassDefFoundError: org/apache/http/protocol/HttpContext
at com.xl.MbbI.config.HTTPConfiguration.clientHttpRequestFactory(HTTPConfiguration.java:25) ~[classes/:na]
at com.xl.MbbI.config.HTTPConfiguration.restTemplate(HTTPConfiguration.java:21) ~[classes/:na]
at com.xl.MbbI.config.HTTPConfiguration$$EnhancerBySpringCGLIB$$191f99f.CGLIB$restTemplate$0(<generated>) ~[na:na]
at com.xl.MbbI.config.HTTPConfiguration$$EnhancerBySpringCGLIB$$191f99f$$FastClassBySpringCGLIB$$8330ce57.invoke(<generated>) ~[na:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.0.RC2.jar:4.3.0.RC2]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.3.0.RC2.jar:4.3.0.RC2]
at com.xl.MbbI.config.HTTPConfiguration$$EnhancerBySpringCGLIB$$191f99f.restTemplate(<generated>) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_60]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.7.0_60]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.7.0_60]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.7.0_60]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.0.RC2.jar:4.3.0.RC2]
... 24 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.apache.http.protocol.HttpContext
at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.7.0_60]
at java.net.URLClassLoader$1.run(Unknown Source) ~[na:1.7.0_60]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_60]
at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.7.0_60]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.7.0_60]
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.7.0_60]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.7.0_60]
... 36 common frames omitted

FYI the error is much more than displayed above.

The first line is something like:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restTemplate' defined in class path resource .....
like image 437
Shofwan Avatar asked Aug 04 '16 23:08

Shofwan


People also ask

Is RestTemplate deprecated in Spring boot?

RestTemplate provides a synchronous way of consuming Rest services, which means it will block the thread until it receives a response. RestTemplate is deprecated since Spring 5 which means it's not really that future proof. First, we create a Spring Boot project with the spring-boot-starter-web dependency.

How does Spring boot handle RestTemplate exception?

Default Error Handling By default, the RestTemplate will throw one of these exceptions in the case of an HTTP error: HttpClientErrorException – in the case of HTTP status 4xx. HttpServerErrorException – in the case of HTTP status 5xx. UnknownHttpStatusCodeException – in the case of an unknown HTTP status.

Is WebClient better than RestTemplate?

Compared to RestTemplate , WebClient has a more functional feel and is fully reactive. Since Spring 5.0, RestTemplate is deprecated. It will probably stay for some more time but will not have major new features added going forward in future releases. So it's not advised to use RestTemplate in new code.


1 Answers

Caused by: java.lang.NoClassDefFoundError: org/apache/http/protocol/HttpContext

The error shows that there was a problem with your classpath, it could be because there is no class or.apache.http.protocol.HttpContext in your classpath. This class is often used by Spring RestTemplate. Normally we can find this class in the Apache httpclient library. You should check again your dependencies. If you can not find it, you can consider to add below dependency (if you use Maven)

 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
like image 58
NangSaigon Avatar answered Oct 07 '22 08:10

NangSaigon