RestTemplate

时间:2017-05-31 08:15:05

标签: spring rest spring-mvc spring-boot

我在以下配置中链接了[Spring-Boot Rest API]和[Go Rest API]。 虽然目标URI的服务存在,但我打算在可通信的环境中使用RestTemplate进行连接,但不知何故它是404错误。

  • [客户]< - (1) - > [Spring-Boot Rest API]< - (2) - > [Go Rest API]< - (3) - > [dB]的

  • [客户]< ---------------------------------(2) - &GT ; [Go Rest API]< - (3) - > [DB]

首先,沟通(2)是正常的

终端可以使用以下cURL命令获取[Go Rest API]的Rest服务。

$ curl http://localhost:18000/ping -X GET
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100   120  100   120    0     0    480      0 --:--:-- --:--:-- --:--:--   591
{"pong":"ok","meta":{"host":"622c72386c52","rid":"","StartTime":"2017-05-31T06:33:37.654710044Z","execute_time":0.0061}}

我想在正面使用[Spring-Boot Rest API]并在内部使用RestTemplate来访问上述URL。 编码如下。

@RequestMapping(value = "/ping/", method = RequestMethod.POST)
public final ResponseEntity<ResPongDto> ping(@RequestBody SalesSituationInquiries input) {

    String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
    this.logger.info("■■UT:[{}]disposalDate:{}   ", methodName,input.getDisposalDate());
    // ①To   Client Response:ResPongDto
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    // ②From Client Request:SalesSituationInquiries
    this.logger.info("■■UT:[{}] From: {} To: {}", methodName,TotalSalesUtil.getStrFromByTo(input.getDisposalDate().toString()),input.getDisposalDate().toString());
    this.logger.info("■■UT:[{}] URL: {}", methodName,DailyReportsUtil.API_GO_PING_URL);
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    // ③To   Go Rest API Request:null
    // ④From Go Rest API Response:ResPongDto
    ResponseEntity<ResPongDto> resultGoMonth = restTemplate.exchange(
            TotalSalesUtil.createTotalSalesUrl(DailyReportsUtil.API_GO_PING_URL, "", "")
            , HttpMethod.GET
            , new HttpEntity<>(null)
            , ResPongDto.class);
    this.logger.info("■■UT:[{}] testRestTemplate.exchange(): ", methodName);

    result = new ResponseEntity<ResPongDto>(resultGoMonth.getBody(), headers, HttpStatus.CREATED);
    return result;
}

(2)via(1) 不幸的是,结果是404错误。

2017-05-31 15:35:43.190 [maekawa-PC-main]                   INFO  Exp:[id: tenant_id:] j.c.b.b.a.BlCloudApplication Started BlCloudApplication in 5.61 seconds (JVM running for 10.472)
2017-05-31 15:38:50.700 [maekawa-PC-http-nio-9999-exec-1]   WARN  Exp:[id: tenant_id:] j.c.b.b.a.i.YamlAuthenticationProcessingMockInterceptor YamlAuthenticationProcessingMockInterceptor:モック機能が動作しています。
2017-05-31 15:38:50.767 [maekawa-PC-http-nio-9999-exec-1]   INFO  Exp:[id: tenant_id:] j.c.b.b.m.r.a.TotalSalesStatusCommandService ■■UT:[ping]disposalDate:2017-04-03
2017-05-31 15:38:50.770 [maekawa-PC-http-nio-9999-exec-1]   INFO  Exp:[id: tenant_id:] j.c.b.b.m.r.a.TotalSalesStatusCommandService ■■UT:[ping] From: 2017-04-01 To: 2017-04-03
2017-05-31 15:38:50.770 [maekawa-PC-http-nio-9999-exec-1]   INFO  Exp:[id: tenant_id:] j.c.b.b.m.r.a.TotalSalesStatusCommandService ■■UT:[ping] URL: http://localhost:18000/ping
2017-05-31 15:38:50.868 [maekawa-PC-http-nio-9999-exec-1]   ACS   Exp:[id: tenant_id:] url:/api/v1/totalsalesstatus/ping/ status:200 elapsedNanoTime:146217390
2017-05-31 15:38:50.871 [maekawa-PC-http-nio-9999-exec-1]   ERROR  o.a.c.c.C.[.[.[.[dispatcherServlet] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing 
failed; nested exception is org.springframework.web.client.HttpClientErrorException: 404 Not Found] with root cause

org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    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.exchange(RestTemplate.java:531)
    at jp.co.broadleaf.blcloud.management.report.api.TotalSalesStatusCommandService.ping(TotalSalesStatusCommandService.java:90)
    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:116)
    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:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    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:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    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:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    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:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    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:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    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:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    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)

注意:

(2)curl http://localhost:18000/ping -X GET

(1)curl http://localhost:9999/api/v1/totalsalesstatus/ping/ -X POST -H“Content-Type:application / json”-d'{“blTenantId”:“1234”,“disposalDate”:“2017-04-03”} “

我不知道为什么他们不与cURL沟通,所以请帮助我。

4 个答案:

答案 0 :(得分:1)

您是否尝试过使用getForEntity代替exchange

ResponseEntity<ResPongDto> resultGoMonth = restTemplate.getForEntity(
        TotalSalesUtil.createTotalSalesUrl(DailyReportsUtil.API_GO_PING_URL, "", "")
        , ResPongDto.class);

我猜你的问题是你没有设置正确的标题。您可以尝试将accept标头添加到请求中。

final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

HttpEntity entity = new HttpEntity(headers);
ResponseEntity<ResPongDto> resultGoMonth = restTemplate.exchange(
            TotalSalesUtil.createTotalSalesUrl(DailyReportsUtil.API_GO_PING_URL, "", ""),
            HttpMethod.GET,
            entity,
            ResPongDto.class);

此代码尚未经过测试。这只是一个例子。

顺便说一句,我不知道你是如何创建resttemplate对象的,但你不应该更新转换器。它应该只在初始化点完成,因为resttemplate一旦创建就不是线程安全的。

答案 1 :(得分:0)

尝试以下代码。这个consumes application / json为body,produces为json响应。

@RequestMapping(value = "/ping", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public final ResponseEntity<ResPongDto> ping(@RequestBody SalesSituationInquiries input) {
    ..
}

答案 2 :(得分:0)

尝试一下。我也遇到了同样的错误。该问题是由于编码错误引起的。

lr = 0.1

答案 3 :(得分:0)

我为这个异常付出了很多努力,即使URL是绝对正确的,相对URL也适用于POST请求。 404表示由于查询参数或请求参数或路径参数,在RestTemplate或HttpRequest中为GET类型方法指定的URL 不正确。原因查询/路径参数的值包含转换或解释不同的特殊字符。说 queryParams是email=test@xyz.com,已转换为email = test20%xyz41%.com

解决方案:传递查询/路径参数时进行解码。

在服务器端添加以下代码[控制器代码]

ServerSide [Controller]:

import java.net.URLDecoder;
                         import java.net.URLEncoder;

String encodedEmail = URLDecoder.decode(email, "UTF-8");

这是完美的工作和经过测试的代码。