web-dev-qa-db-fra.com

Pourquoi ai-je toujours 403 lors de la récupération de données avec RestTemplate?

J'essaie d'extraire des données mais j'obtiens toujours 403(Forbidden) avec RestTemplate.

Mais quand j'essaie org.Apache.http.client.HttpClient à la place, tout va bien. Je peux également obtenir des données avec Postman sur ma machine.

Le code est assez simple mais je ne sais pas ce qui ne va pas.

public Object get() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
            return result;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return null;
        }
    }

EDIT: ajout trace de pile

org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.Java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.Java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.Java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.Java:613)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.Java:287)
    at com.brawlstone.metaservice.service.SyncService.get(SyncService.Java:49)
    at com.brawlstone.metaservice.web.SyncController.getCards(SyncController.Java:30)
    at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:62)
    at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:43)
    at Java.lang.reflect.Method.invoke(Method.Java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.Java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.Java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.Java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.Java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.Java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.Java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.Java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.Java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.Java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.Java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.Java:622)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.Java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.Java:729)
    at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:292)
    at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
    at org.Apache.Tomcat.websocket.server.WsFilter.doFilter(WsFilter.Java:52)
    at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:240)
    at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.Java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
    at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:240)
    at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.Java:105)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
    at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:240)
    at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.Java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
    at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:240)
    at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.Java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
    at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:240)
    at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.Java:115)
    at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.Java:59)
    at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.Java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
    at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.Java:108)
    at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:240)
    at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:207)
    at org.Apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.Java:212)
    at org.Apache.catalina.core.StandardContextValve.invoke(StandardContextValve.Java:106)
    at org.Apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.Java:502)
    at org.Apache.catalina.core.StandardHostValve.invoke(StandardHostValve.Java:141)
    at org.Apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.Java:79)
    at org.Apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.Java:616)
    at org.Apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.Java:88)
    at org.Apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.Java:522)
    at org.Apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.Java:1095)
    at org.Apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.Java:672)
    at org.Apache.Tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.Java:2500)
    at org.Apache.Tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.Java:2489)
    at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1142)
    at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:617)
    at org.Apache.Tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.Java:61)
    at Java.lang.Thread.run(Thread.Java:745)
22
Kanjie Lu

Essayez d'ajouter un en-tête "User-Agent" à votre demande.

Changez votre code pour:

try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
            HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

            Object response = restTemplate.exchange("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", HttpMethod.GET,entity,Object.class);

            System.out.println(response);
        } catch (Exception ex) {
           ex.printStackTrace();

        }
23
Tanmay Delhikar

Vous essayez d'accéder à https sans configurer RestTemplate pour utiliser un certificat SSL pour la requête

Essayez d'utiliser la configuration suivante de RestTemplate

CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLHostnameVerifier(new NoopHostnameVerifier())
                    .build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
....
9
Zico