我是 dropwizard 的新手。我正在使用 dropwizard 的 0.8.5 版。我有一个 dropwizard REST 服务,它在调用成功时返回 JSON,在调用不成功时返回 HTTL,例如 HTTP 状态代码 500 或 404。
幸福之路
LOGGER.info("Cached userinfo for '{}'",username);
JSONObject json = new JSONObject();
json.put("ticketId",created.getTicketId());
json.put("token", token);
return Response.ok(json.toString()).build();
Run Code Online (Sandbox Code Playgroud)
不幸的道路
if (created.getTicketId() == null) {
LOGGER.error("Email not sent, ticket not created");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).type(MediaType.APPLICATION_JSON).build();
}
Run Code Online (Sandbox Code Playgroud)
这是卷曲:
curl -H "Content-Type: application/json" -X POST -d '{"username":"WPf3s0G1M"}' http://localhost:7777/ids-rest-api/password/reset
Run Code Online (Sandbox Code Playgroud)
这是那个 curl 的回复,我想要 JSON 格式的回复:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 500 Request failed.</title>
</head>
<body><h2>HTTP ERROR 500</h2>
<p>Problem accessing /ids-rest-api/password/reset. Reason:
<pre> Request failed.</pre></p><hr><i><small>Powered by Jetty://</small> </i><hr/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果您将实体添加到响应中,您的方法将起作用,即使它是一个空的 JSON 对象,例如
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/error")
@Produces(MediaType.APPLICATION_JSON)
public class BrokenResource {
@GET
public Response getServerError() {
return Response.serverError().entity("{}").build();
}
}
Run Code Online (Sandbox Code Playgroud)
如果方法或类使用@Produces(MediaType.APPLICATION_JSON) 进行注释,则可以删除明确说明类型以节省一些时间。
| 归档时间: |
|
| 查看次数: |
1758 次 |
| 最近记录: |