无法从REST请求获得响应 - 使用Spring Bean的Java NetBeans

时间:2016-09-14 16:57:17

标签: java json spring rest netbeans

我正在尝试学习如何使用Java在NetBeans中使用Spring进行REST服务。

在我的应用程序中,我创建了一个bean并在我的pom.xml文件中放入了依赖项。

当我提出我的请求时(我知道当我在浏览器中输入它并返回JSON时),我收到以下错误:

--- exec-maven-plugin:1.2.1:exec (default-cli) @ AutoNGplusAPITest ---
Exception in thread "AWT-EventQueue-0" org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [text/html;charset=utf-8]
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:773)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:758)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:535)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:489)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:431)
    at com.blackstonesoftwaretechnologies.startPage.sendURIActionPerformed(startPage.java:467)
    at com.blackstonesoftwaretechnologies.startPage.access$800(startPage.java:26)
    at com.blackstonesoftwaretechnologies.startPage$9.actionPerformed(startPage.java:218)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 19.966s
Finished at: Wed Sep 14 11:15:07 EDT 2016
Final Memory: 6M/106M

以下是我正在运行的Java类文件中传递REST调用的代码:

private void sendURIActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        String link, api = null;
        link = parseString(endpointAPI.getText());
        shortResults.setText("URI under Test is: " + String.valueOf(link) + ". \n" + "Please wait ..." + "\n\n\n" + "Results: " + "\n");
        //api = parseString(endpointAPI.getText());

        Object[] row = {link, "", "200", ""};
        DefaultTableModel model = (DefaultTableModel) parameterTable.getModel();
        model.addRow(row);

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders requestHeaders = new HttpHeaders();

        requestHeaders.add("Content-Type","application/json");

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

        String tokenaccess = "";
        String apiUndertest1 = restTemplate.exchange(link, HttpMethod.GET, request, String.class).getBody();
        Map result = restTemplate.exchange(link, HttpMethod.GET, request, Map.class).getBody();

        shortResults.append(apiUndertest1);

    }                                       

我缺少什么? 我假设在pom.xml文件中,我下载的spring依赖项将处理JSON转换。

我使用的示例网址是:https://github.comhttp://jsonplaceholder.typicode.com/posts/1

有人可以帮助我理解我犯了错误的地方并告诉我如何纠正它(缺少代码,代码结构等)。我真的想要正确地学习这一点。

由于

2 个答案:

答案 0 :(得分:1)

Spring rest模板不会自动将JSON映射到对象。你必须明确定义它。使用Jackson(核心,数据绑定,注释)。将以下内容放在调度程序servlet中:

<beans:bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonMessageConverter" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <!-- Configure bean to convert JSON to POJO and vice versa -->
    <beans:bean id="jsonMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    </beans:bean>

这将负责将JSON转换为Class对象,反之亦然。

这应该是理所当然的。

答案 1 :(得分:0)

您希望Spring RestTemplate会自动将结果解析为Java对象(在您的情况下为Map)。事实并非如此。

您必须为RestTemplate提供它应尝试使用的转换器列表。在大多数情况下,您应该使用MappingJackson2HttpMessageConverter

RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter> messageConverters = new ArrayList<>();
messageConverters.add(new MappingJackson2HttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);    

为此,你还应该将Jackson添加到你的pom.xml中:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.2</version>
</dependency>