Spring 关于RestTemplate

Spring 关于RestTemplate,spring,rest,spring-mvc,spring-boot,Spring,Rest,Spring Mvc,Spring Boot,我在以下配置中链接了[Spring Boot Rest API]和[Go Rest API]。 虽然目标URI的服务存在,但我打算在可通信的环境中使用RestTemplate进行连接,但不知何故,这是一个404错误 2017-05-31 15:35:43.190 [maekawa-PC-main] INFO Exp:[id: tenant_id:] j.c.b.b.a.hogehogeApplication Started hogehogeApplicati

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

2017-05-31 15:35:43.190 [maekawa-PC-main]                   INFO  Exp:[id: tenant_id:] j.c.b.b.a.hogehogeApplication Started hogehogeApplication 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 xx.xx.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)
  • [客户端][Spring Boot Rest API][Go Rest API][数据库]

  • [客户端][Go Rest API][数据库]

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

[Go Rest API]的Rest服务可通过以下cURL命令从终端获得

$ 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) curl-xget

(1) curl-X POST-H“内容类型:application/json”-d'{“hoghoge”:“1234”,“disposalDate”:“2017-04-03”}”

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

尝试下面的代码。此应用程序/json作为主体和json响应

@RequestMapping(value = "/ping", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public final ResponseEntity<ResPongDto> ping(@RequestBody SalesSituationInquiries input) {
    ..
}
@RequestMapping(value=“/ping”,method=RequestMethod.POST,products=“application/json”,consumes=“application/json”)
公共最终响应标题ping(@RequestBody SalesSituationQuiries输入){
..
}

您是否尝试过使用
getForEntity
而不是
exchange

ResponseEntity<ResPongDto> resultGoMonth = restTemplate.getForEntity(
        TotalSalesUtil.createTotalSalesUrl(DailyReportsUtil.API_GO_PING_URL, "", "")
        , ResPongDto.class);
ResponseEntity resultGoMonth=restemplate.getForEntity(
TotalSalesUtil.createTotalSalesUrl(dailReportSutil.API\u GO\u PING\u URL,“,”)
,分别为第二级);
我想你的问题是你没有设置正确的标题。您可以尝试将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);
final-HttpHeaders-HttpHeaders=new-HttpHeaders();
setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity=新的HttpEntity(标题);
ResponseEntity resultGoMonth=restemplate.exchange(
TotalSalesUtil.createTotalSalesUrl(dailReportSutil.API_GO_PING_URL,“,”),
HttpMethod.GET,
实体,
相应的类别);
此代码尚未经过测试。这只是一个例子


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

试试这个。我也犯了同样的错误。该问题是由不正确的编码引起的

public String getWeather(String cityName) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(weatherDataURL)
                                                       .queryParam("q", cityName)
                                                       .queryParam("APPID", apiKey);
    return restTemplate.getForObject(builder.buildAndExpand().toUri(), String.class);
}

我为这个例外挣扎了很多,即使URL是绝对正确的,相对URL也适用于POST请求。 404表示RestTemplate或HttpRequest中为GET type方法指定的URL不正确,原因是查询参数或请求参数或路径参数。原因查询/路径参数的值包含以不同方式转换或解释的特殊字符。 查询参数是电子邮件=test@xyz.com转换为email=test20%xyz41%.com

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

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

服务器端[控制器]:

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

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

它完美地运行并测试了代码。

我自己解决了这个问题。我在内部编辑了URL,并在将其作为参数从URI的组成元素中传递出去时,将“/”作为后缀添加到参数中。结果,“/ping”被重写为“/ping/”,404在[Go Rest API]端被吐出,该端将其视为不同的项。当以“/ping”的形式传递时,它能够正确地获取。非常感谢你,苏达卡。