如何解决415不支持的媒体类型错误?

时间:2018-04-19 05:23:37

标签: java json angular rest jax-rs

我有角度5尝试将PUT请求发送到java应用程序中的休息服务:

Angular电话:

    ...
    import 'rxjs/add/operator/toPromise';

    const httpOptions = {
        headers: new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'application/json' })
    };

    @Injectable()
    export class TripService {

...

    saveTrip(trip: Trip): Observable<any> {
    return this.http.put(`${this.baseUrl}/Trip`, JSON.stringify(trip), httpOptions);
  }

服务器(java)服务:

@PUT
@Consumes("application/json")
public Response updateTrip(Trip trip) {
    tripDao.updateTrip(trip);
    return Response.ok().entity("trip updated successfully").build();
}

实体!:

@Entity
@Table(name = "trip")
@XmlRootElement
public class Trip implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    @XmlElement(name = "id")
    private Integer id;
    @XmlElement(name = "user")
    private User user;
    @XmlElement(name = "start_date")
    private Date startDate;
    ...

请求标题:

Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,he;q=0.8
Authorization: Bearer fake-jwt-token
Connection: keep-alive
Content-Length: 538
Content-Type: application/json
Host: localhost:8080
Origin: http://localhost:4200
Referer: http://localhost:4200/manager/company
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 

错误:

Request URL: http://localhost:8080/... /rest/Trip
Request Method: PUT
Status Code: 415 Unsupported Media Type
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade

我需要有关JSON到Java转换的帮助吗?我有这个jar例如: javax.ws.rs-API-2.0.1

我添加了目前包含在项目中的杰克逊罐子: jackson jars

2 个答案:

答案 0 :(得分:1)

您的客户端在其application/json标头中请求Accept,但服务器不会生成它。添加Produces注释,声明支持内容类型。

@PUT
@Consumes("application/json")
@Produces("application/json")
public Response updateTrip(Trip trip) {

除此之外,您的服务器没有使用JSON响应,这完全是另一个问题。您可能希望使用以下方法注释该方法:

@Consumes("text/plain") 

您需要的最有可能的解决方法是让您的客户发送Accept: */*Accept: text/plain

答案 1 :(得分:-1)

使用杰克逊

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

除非您有任何特定情况,否则它可以将您的XML响应转换为JSON而无需任何其他代码。