无法使用POST请求和Jackson发送JSON

时间:2016-06-17 14:59:58

标签: java json spring hibernate post

这是我的实体类:

 httpput.setEntity(new StringEntity(
    "{\"comments\":\"" + comm + "\",\"displaynumber\":\"" + tcn
      + "\",\"order\":\"" + orderAdd + "\"}",
        ContentType.create("application/json")));

 response = httpClient.execute(target, httpput);

}

这是我的根本背景:

@Entity
@Table(name = "menuitem")
public class MenuItem {

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY )
@Column(name = "id")
private Integer id;

@Column(name = "title")
private String title;

@Column(name = "eng_title")
private String engTitle;

@Column(name = "price")
private double price;

@Column(name = "description")
private String description;

@Column(name = "consist_of")
private String consistOf;

@Column(name = "volume_value")
private double volumeValue;

@Column(name = "volume_title")
private String volumeTitle;

@ManyToOne
@JoinColumn(name = "category_id",insertable = false, updatable = false)
private Category category;

@Column(name = "category_id")
private int categoryId;

public MenuItem() {

}

public MenuItem(JSONObject jsonObject) {
    if (!jsonObject.isNull("id")) {
        this.id = jsonObject.getInt("id");
    }

    if (!jsonObject.isNull("title")) {
        this.title = jsonObject.getString("title");
    }

    if (!jsonObject.isNull("engTitle")) {
        this.engTitle = jsonObject.getString("engTitle");
    }

    if (!jsonObject.isNull("price")) {
        this.price = jsonObject.getDouble("price");
    }

    if (!jsonObject.isNull("description")) {
        this.description = jsonObject.getString("description");
    }

    if (!jsonObject.isNull("consistOf")) {
        this.consistOf = jsonObject.getString("consistOf");
    }

    if (!jsonObject.isNull("volumeValue")) {
        this.volumeValue = jsonObject.getDouble("volumeValue");
    }

    if (!jsonObject.isNull("volumeTitle")) {
        this.volumeTitle = jsonObject.getString("volumeTitle");
    }
}

public MenuItem(Integer id, String title, String engTitle, double price,
        String description, String consistOf, double volumeValue,
        String volumeTitle) {
    super();
    this.id = id;
    this.title = title;
    this.engTitle = engTitle;
    this.price = price;
    this.description = description;
    this.consistOf = consistOf;
    this.volumeValue = volumeValue;
    this.volumeTitle = volumeTitle;
}



@Override
public String toString() {
    return "MenuItem [id=" + id + ", title=" + title + ", engTitle="
            + engTitle + ", price=" + price + ", description="
            + description + ", consistOf=" + consistOf + ", volumeValue="
            + volumeValue + ", volumeTitle=" + volumeTitle + ", categoryId=" + categoryId + "]";
}

public String getEngTitle() {
    return engTitle;
}

public void setEngTitle(String engTitle) {
    this.engTitle = engTitle;
}

public void setId(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getConsistOf() {
    return consistOf;
}

public void setConsistOf(String consistOf) {
    this.consistOf = consistOf;
}

public double getVolumeValue() {
    return volumeValue;
}

public void setVolumeValue(double volumeValue) {
    this.volumeValue = volumeValue;
}

public String getVolumeTitle() {
    return volumeTitle;
}

public void setVolumeTitle(String volumeTitle) {
    this.volumeTitle = volumeTitle;
}

@JsonBackReference
@JsonIgnore
public Category getCategory() {
    return category;
}

public void setCategory(Category category) {
    this.category = category;
}   

public void setCategoryId(int categoryId) {
    this.categoryId = categoryId;
}

这是我的控制者:

<beans:bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:array>
                <beans:bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <beans:property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
                </beans:bean>
            </beans:array>
        </beans:property>
    </beans:bean>

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <!-- Configure to plugin JSON as request and response in method handler -->
    <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>

    <mvc:interceptors>
        <beans:bean class="ru.tenet.cafe.interceptor.LoginInterceptor" />
    </mvc:interceptors>

    <context:component-scan base-package="ru.tenet.cafe" />

    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="transactionManager" />

    <beans:bean id="dataSourceMain" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <beans:property name="driverClass" value="org.postgresql.Driver" />
        <beans:property name="jdbcUrl"
            value="jdbc:postgresql://192.168.101.158:5432/cafe" />
        <beans:property name="user" value="postgres" />
        <beans:property name="password" value="123" />
        <beans:property name="minPoolSize" value="5" />
        <beans:property name="maxPoolSize" value="8" />
        <beans:property name="preferredTestQuery" value="SELECT 1" />
        <beans:property name="acquireIncrement" value="1" />
        <beans:property name="idleConnectionTestPeriod" value="100" />
        <beans:property name="maxStatements" value="0" />
        <beans:property name="checkoutTimeout" value="60000" />
    </beans:bean>

    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSourceMain" />
        <beans:property name="configLocation">
            <beans:value>/WEB-INF/db/hibernate.cfg.xml</beans:value>
        </beans:property>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.connection.characterEncoding">UTF-8</beans:prop>
                <beans:prop key="hibernate.connection.charSet">UTF-8</beans:prop>
                <beans:prop key="hibernate.connection.useUnicode">true</beans:prop>
                <beans:prop key="hibernate.show_sql">false</beans:prop>
            </beans:props>
        </beans:property>

    </beans:bean>



    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>

但是如果我发送带有以下正文的POST请求

@RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> create(
            @RequestBody MenuItem menuItem) {   
        menuService.create(menuItem);
        return new ResponseEntity<String>(HttpStatus.OK);

    }

我会得到:

  

415服务器拒绝了此请求,因为请求实体位于   所请求的请求资源不支持的格式   方法

到底是什么?

2 个答案:

答案 0 :(得分:2)

让我们从一个小定义开始:

  

415 不支持的媒体类型

     

请求实体具有媒体类型   服务器或资源不支持。例如,客户端   将图像上传为image / svg + xml,但服务器需要图像   使用不同的格式。

可以通过以下方式解决:

@RequestMapping(value = "", method = RequestMethod.POST, produces = "application/json; charset=UTF-8", consumes = "application/json; charset=UTF-8")

说明:基本上,您需要指定端点将要使用/生成的数据类型。发送请求以指定标题时不要忘记

Content-Type: application/json

答案 1 :(得分:0)

您的当前控制器必须替换为以下代码:

@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<String> create() {
    MenuItem menuItem = null;
    menuService.create(menuItem); // Fill in the menuItem
    // Now respond
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(menuItem, responseHeaders, HttpStatus.OK);
}