如果设置了mediaType,为什么我会收到HttpClientErrorException 406?

时间:2017-07-04 09:03:27

标签: spring content-type resttemplate http-status-code-406

Collegues,我有将post请求发送到Web服务的方法

public void postPmnt(Document doc) throws TransformerException, HttpServerErrorException {

        RestTemplate rt = new RestTemplate();

        String uri = new String(environment.getProperty("rest.server.endpoint") + environment.getProperty("rest.server.resource"));

        String body = pmonCommons.xmlDocToString(doc);


        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.APPLICATION_XML);
            stringHttpMessageConverter.setSupportedMediaTypes(mediaTypes);

        messageConverters.add(stringHttpMessageConverter);
        rt.setMessageConverters(messageConverters);

        rt.getInterceptors().add(new BasicAuthorizationInterceptor(environment.getProperty("rest.server.user"), environment.getProperty("rest.server.pass")));

//        rt.getInterceptors().add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_XML_VALUE));
//        rt.getInterceptors().add(new HeaderRequestInterceptor("Content-Type", MediaType.APPLICATION_XML_VALUE));


//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_XML);
//        headers.setAccept(mediaTypes);

        HttpEntity<String> request = new HttpEntity<>(body);

         log.info("Call rt");
        // ResponseEntity<String> response = rt.postForEntity(uri, request, String.class);
         ResponseEntity<String> response = rt.exchange(uri, HttpMethod.POST, request, String.class);

        }
}

如你所见,我试图使用一些不同的代码变体,但结果是一样的。

stacttrace看起来像:

10:59:55.645 DEBUG [main] o.s.c.e.PropertySourcesPropertyResolver - Found key 'rest.server.pass' in [class path resource [pmon-dev.properties]] with type [String]
10:59:55.647 INFO  [main] com.pivotal.pmon.rest.Client - Call rt
10:59:55.667 DEBUG [main] o.s.web.client.RestTemplate - Created POST request for "https://uat.pivotal.com/API/Pay"
10:59:55.668 DEBUG [main] o.s.web.client.RestTemplate - Setting request Accept header to [application/xml]
10:59:55.668 DEBUG [main] o.s.web.client.RestTemplate - Writing [<?xml version="1.0" encoding="UTF-8"?><Document>....
data...
</Document>
] using [org.springframework.http.converter.StringHttpMessageConverter@5012c571]
10:59:56.992 DEBUG [main] o.s.web.client.RestTemplate - POST request for "https://uat.pivotal.com/API/Pay" resulted in 406 (null); invoking error handler
10:59:56.997 TRACE [main] o.s.test.context.TestContextManager - afterTestMethod(): instance [com.pivotal.pmon.rest.ClientTest@69b794e2], method [public void com.pivotal.pmon.rest.ClientTest.postPmnt() throws java.lang.Exception], exception [org.springframework.web.client.HttpClientErrorException: 406 null]
10:59:56.998 DEBUG [main] o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@ba8d91c testClass = ClientTest, testInstance = com.pivotal.pmon.rest.ClientTest@69b794e2, testMethod = postPmnt@ClientTest, testException = org.springframework.web.client.HttpClientErrorException: 406 null, mergedContextConfiguration = [MergedContextConfiguration@7364985f testClass = ClientTest, locations = '{}', classes = '{class com.pivotal.pmon.pmonConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].

org.springframework.web.client.HttpClientErrorException: 406 null

    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 com.pivotal.pmon.rest.Client.postPmnt(Client.java:84)
    at com.pivotal.pmon.rest.ClientTest.postPmnt(ClientTest.java:83)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

10:59:57.009 TRACE [main] o.s.test.context.TestContextManager - afterTestClass(): class [com.pivotal.pmon.rest.ClientTest]
10:59:57.009 DEBUG [main] o.s.t.c.s.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@ba8d91c testClass = ClientTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@7364985f testClass = ClientTest, locations = '{}', classes = '{class com.pivotal.pmon.pmonConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].
10:59:57.012 INFO  [Thread-1] o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support......
Process finished with exit code -1

为什么我收到406错误? 是因为客户端无法解析响应吗? 如何避免此错误并阅读(打印)响应?

P.S。如果我从SoapUI发送请求比它工作正常。在请求标头的Content-Type中:application / xml; charset = UTF-8。方法:发布 原始响应如下:

HTTP/1.1 400 
Server: nginx/1.6.2
Date: Tue, 04 Jul 2017 06:56:15 GMT
Content-Type: application/xml
Content-Length: 734
Connection: keep-alive
X-Application-Context: pus.app.AuthProxy:test,db-vfactdb:8080
X-Frame-Options: DENY
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-Content-Type-Options: nosniff
Expires: 0
Pragma: no-cache
X-Application-Context: currency-pay:default:8080
X-XSS-Protection: 1; mode=block

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Document>...</Document>

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为您使用的Web服务不仅接受XML而且还返回XML。 您可以定义与Web服务返回的XML对应的POJO。我认为你已经创建了这个POJO并且是类Document。

因此,对Web服务的调用应该是

ResponseEntity<Document> response = rt.exchange(uri, HttpMethod.POST, request, Document.class);

如果这解决了您的问题,请告诉我。