我正在使用Netbeans的RESTful Web服务开发Web服务。服务类包含以下方法:

@Path("jpost")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String jpost(Car c){
    return "Car:"+c.getTag()+"\t"+c.getName()+"\t"+c.getColor();
}


为了测试此方法,我使用Netbeans的RESTful Java Client生成测试方法。结果是:

public String jpost(Object requestEntity) throws ClientErrorException {
        return webTarget.path("jpost").request(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON), String.class);
    }


当我致电jpost时,出现以下错误:

Exception in thread "main" javax.ws.rs.NotAcceptableException: HTTP 406 Not Acceptable
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:923)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:770)
    at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:90)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:671)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:422)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:667)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:423)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:326)
    at myserver.test5.jpost(test5.java:36)
    at myserver.MyServerTest.main(MyServerTest.java:32)


问题是什么?

最佳答案

您的服务仅产生text/plain响应。

HTTP代码406表示服务器无法提供客户端可以接受的内容类型。因此,客户端要么在Accepts标头中指定了错误的内容类型,要么根本没有发送Accepts

要指定可接受的类型,请使用request(...)参数。

public String jpost(Object requestEntity) throws ClientErrorException
{
    return webTarget.path("jpost")
            .request(javax.ws.rs.core.MediaType.TEXT_PLAIN)
            .post(javax.ws.rs.client.Entity.entity(requestEntity, javax.ws.rs.core.MediaType.APPLICATION_JSON), String.class);
}

关于java - Netbeans的RESTful Java客户端:javax.ws.rs.NotAcceptableException:HTTP 406 Not Acceptable ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43172247/

10-12 02:04