将POJO发布到其余Web服务时出现415错误

时间:2021-06-26 19:33:34

i've been developing a web service using jackson on the server side of the system and accessing it using jersey which is working fine for the get requests however I am running into a brick wall when attempting to post a POJO to the web service as it keeps returning a 415 error.

我一直在系统的服务器端使用jackson开发一个Web服务,并使用jersey访问它,这对于get请求工作正常但是当我尝试将POJO发布到Web服务时,我遇到了问题。继续返回415错误。

Server side code which parses the POST request:

解析POST请求的服务器端代码:

    public View addFarmer(@RequestBody Farmer farmer) {
        farmerService.saveFarmer(farmer);
        return new RedirectView("/farmerView/"+ farmer.getFarmerId());
    }

Client side class which handles communication with the service:

处理与服务通信的客户端类:

    public Status addFarmer(Farmer farmer) throws UniformInterfaceException, IOException {
        ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, farmer);
        return response.getClientResponseStatus();
    }

Client side POJO being sent to server:

客户端POJO被发送到服务器:

   @XmlRootElement(name="Farmer")
   public class Farmer implements Serializable {
   private Integer farmerId;
   private String farmerName;

   public Farmer() {   }

   public Farmer(Integer farmerId) {
       this.farmerId = farmerId;
   }

    public Integer getFarmerId() { return farmerId; }
    public void setFarmerId(Integer farmerId) { this.farmerId = farmerId; }
    public String getFarmerName() { return farmerName; }
    public void setFarmerName(String farmerName) { this.farmerName = farmerName; } 

}

Client side test case:

客户端测试用例:

   public void testAddFarmer() throws Exception {
        System.out.println("addFarmer");
        FarmerRestClient instance = new FarmerRestClient();
        Farmer farmer = new Farmer() ;
        farmer.setFarmerId(4);
        farmer.setFarmerName("farmer4");
        Status result = instance.addFarmer(farmer);
        assertEquals("200", result);
       System.out.println(result);
    }

Testing the save functionality using a POJO on the server side works correctly so i'm assumming its something simple which i'm missing when attempting to save the POJO however research on POSTing a POJO to a rest client seems to come up short on examples. I am relatively new to Jackson and Jersey.

在服务器端使用POJO测试保存功能可以正常工作,所以我在尝试保存POJO时会忘记一些简单的事情,但是关于将POJO发布到休息客户端的研究似乎很少见。我对杰克逊和泽西岛来说比较新。

Any assistance would be greatly appreciated,

任何帮助将不胜感激,

Leanne


I have updated the configuration xml file to look as follows:

我已将配置xml文件更新为如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <mvc:annotation-driven />

    <beans:bean id="farmerView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />

    <beans:bean id="advisorView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />   

    <beans:bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></beans:bean>

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

    <beans:bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <beans:property name="mediaTypes">
            <beans:map>
                <beans:entry key="json" value="application/json" />
            </beans:map>
        </beans:property>
        <beans:property name="viewResolvers">
            <beans:list>
                <beans:bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <resources mapping="/resources/**" location="/resources/" />
    <beans:import resource="controllers.xml" />
    </beans:beans>

And my server side code handling the request to have an accept header as follows:

我的服务器端代码处理请求以具有接受标头,如下所示:

    @RequestMapping(headers="Accept=application/json", method = RequestMethod.POST)
    public View addFarmer(@RequestBody Farmer farmer) {
        farmerService.saveFarmer(farmer);
        return new RedirectView("/farmerView/"+ farmer.getFarmerId());
    }

The client code wasnt sending JSON to the server so I updated it to ensure it was:

客户端代码没有将JSON发送到服务器,所以我更新它以确保它是:

   public Status addFarmer(Farmer farmer) throws UniformInterfaceException, IOException {
        String json = mapper.writeValueAsString(farmer);
        ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, json);
        return response.getClientResponseStatus();
    }

However I am still getting the same error. I am sure this is due to my inexperience with Spring MVC and jackson. I appologise for not mentioning I was using Spring in my original post

但是我仍然得到同样的错误。我确信这是由于我对Spring MVC和jackson缺乏经验。我抱歉没有提到我在原帖中使用了Spring

2 个解决方案

#1


0  

The mvc-showcase has good example of a REST based service.

mvc-showcase具有基于REST的服务的良好示例。

Since you are sending in a farmer (as xml) and expecting back the saved farmer, you should return farmer from your controller and annotate your controller method with @ResponseBody

既然您正在派遣农民(以xml为单位)并期待已保存的农民,您应该从控制器返回农民并使用@ResponseBody注释您的控制器方法

    public @ResponseBody Farmer addFarmer(@RequestBody Farmer farmer) {
        Farmer savedFarmer = farmerService.saveFarmer(farmer);
        return savedFarmer;
    }

The client request should have an Accept header of application/xml or application/json(as appropriate), and your request should go through.

客户端请求应具有application / xml或application / json的Accept标头(视情况而定),并且您的请求应该通过。

#2


0  

It looks like you're using Spring on the server. I expect 415 is the error you'd get if you don't have an HTTP message converter capable of handling JSON content.

看起来你在服务器上使用Spring。如果你没有能够处理JSON内容的HTTP消息转换器,我希望415是你得到的错误。

#1


0  

The mvc-showcase has good example of a REST based service.

mvc-showcase具有基于REST的服务的良好示例。

Since you are sending in a farmer (as xml) and expecting back the saved farmer, you should return farmer from your controller and annotate your controller method with @ResponseBody

既然您正在派遣农民(以xml为单位)并期待已保存的农民,您应该从控制器返回农民并使用@ResponseBody注释您的控制器方法

    public @ResponseBody Farmer addFarmer(@RequestBody Farmer farmer) {
        Farmer savedFarmer = farmerService.saveFarmer(farmer);
        return savedFarmer;
    }

The client request should have an Accept header of application/xml or application/json(as appropriate), and your request should go through.

客户端请求应具有application / xml或application / json的Accept标头(视情况而定),并且您的请求应该通过。

#2


0  

It looks like you're using Spring on the server. I expect 415 is the error you'd get if you don't have an HTTP message converter capable of handling JSON content.

看起来你在服务器上使用Spring。如果你没有能够处理JSON内容的HTTP消息转换器,我希望415是你得到的错误。