REST POST的媒体类型不支持

14

我有这个VO

public class myVO {
    private final String latitude;
    private final String longtitude;
    private final String meterRadius;

    public myVO(String latitude, String longtitude, String meterRadius) {
        this.latitude = latitude;
        this.longtitude = longtitude;
        this.meterRadius = meterRadius;
    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongtitude() {
        return longtitude;
    }

    public String getMeterRadius() {
        return meterRadius;
    }

}

以及REST服务

@Path("/listrs")
@Produces(MediaType.APPLICATION_JSON)
public class MyResource {
    Logger logger = LoggerFactory.getLogger(MyResource.class);

    private final AtomicLong counter;

    public MyResource(String template, String defaultName) {
        //this.template = template;
        //this.defaultName = defaultName;
        this.counter = new AtomicLong();
    }

    @GET
    @Timed
    public List<ResultVO> getMyList() {
        List<ResultVO> list = new ArrayList<>();
        list.add(new ResultVO(counter.incrementAndGet(), "dummy text"));
        list.add(new ResultVO(counter.incrementAndGet(), "dummy text1"));
        return list;
    }

    @POST
    @Timed
    @Consumes(MediaType.APPLICATION_JSON)
    public List<ResultVO> getListByLoc(myVO loc) {
        logger.debug(loc.toString());
        return getMyList();
    }
}

使用测试进行验证

curl -i -X POST -d '{"latitude": "2.3433", "longtitude": "23.2233", "meterRadius":"5"}' http://localhost:8080/listrs

我得到的结果:

curl: (6) Could not resolve host: 2.3433,
curl: (6) Could not resolve host: longtitude
curl: (6) Could not resolve host: 23.2233,
curl: (3) [globbing] unmatched close brace/bracket at pos 14
HTTP/1.1 415 Unsupported Media Type
Date: Sun, 23 Mar 2014 21:23:16 GMT
Content-Type: text/html;charset=ISO-8859-1
Cache-Control: must-revalidate,no-cache,no-store
Content-Length: 1350

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 415 Unsupported Media Type</title>
</head>
<body><h2>HTTP ERROR 415</h2>
<p>Problem accessing /listrs. Reason:
<pre>    Unsupported Media Type</pre></p><br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>

</body>
</html>

你知道我做错了什么吗?我正在使用dropwizard,但我认为这不相关。


它适用于GET curl -i -X GET http://localhost:8080/listrs/。 - StephenNYC
1个回答

33

使用curl执行以下操作:

-H "Content-Type: application/json"

另外一件事,您可能正在运行此操作的 Windows 电脑上。因此,请使用双引号(")而不是单引号(')来包裹您的 JSON。

-d "{\"latitude\": \"2.3433\", \"longtitude\": \"23.2233\", \"meterRadius\":\"5\"}"

请注意,我已经使用\转义了内部引号。

最后,使用带有-v参数的curl。它将帮助您查看curl发送到服务器的内容。


1
谢谢。转义JSON有所帮助。我已经设置了内容类型,只是没有包含它。谢谢! - StephenNYC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接