【发布时间】:2015-04-14 13:34:33
【问题描述】:
帮助!我已经尽我所能,但似乎没有任何效果。我的问题如下:
我有一个 Spring REST 服务,它发出一个 REST 调用,接收一个 base64 编码的 PDF。然后我解码 PDF,并在浏览器中显示它。我可以让这部分完美地工作!但!我在处理 404、500 等时遇到问题。错误消息。
不幸的是,错误消息在 API 中作为哈希映射中的消息返回给我,正如您在下面的逻辑中看到的那样。
我尝试创建 PDF,但无法将其转换为文件对象,我尝试将字节直接流式传输到浏览器,但无论我做什么,它都不适合我。
有没有办法根据逻辑更改响应标头?成功时返回pdf,出错时返回文本文件给浏览器?
我在这里筋疲力尽,不知道该去哪里。任何建议或指示将不胜感激。
我也尝试向浏览器抛出 404,但它需要一个 pdf 文件,我收到 MIME 错误。
@Controller
@Path("/mon")
public class WSController {
@Autowired
Service service;
@GET
@Produces("application/pdf")
@Path("/ws")
public File getWs(@QueryParam("vin") String vin) throws IOException, URISyntaxException {
Map response = service.getWs(vin);
if (response == null) {
return createErrorFile("Server Error, please try again later.");
} else if (response.get("ErrorCode") != null && response.get("ErrorCode").equals("E")) {
return createErrorFile((String) response.get("ErrorDescription"));
} else {
return decodeBase64(((String) response.get("Base64String")).replace("\n",""));
}
}
private File decodeBase64(String encodedFile) throws IOException {
byte[] decodedBytes = DatatypeConverter.parseBase64Binary(encodedFile);
File file = new File("wS.pdf");
FileOutputStream fop = new FileOutputStream(file);
fop.write(decodedBytes);
fop.flush();
fop.close();
return file;
}
private File createErrorFile(String errorDescription) throws IOException {
//Not sure what to do here
return null;
}
编辑:这就是最终为我工作的东西。非常感谢您的建议。这是一次美妙的学习经历。
@GET
@Path("/ws")
public Response getWS(@QueryParam("vin") String vin) throws IOException, URISyntaxException {
Map results = Service.getWS(vin);
if (results == null) {
Response.ResponseBuilder rBuild = Response.status(Response.Status.BAD_REQUEST);
return rBuild.type(MediaType.TEXT_PLAIN)
.entity("Server error, please try again later.")
.build();
} else if (results.get("ErrorCode") != null && results.get("ErrorCode").equals("E")) {
Response.ResponseBuilder rBuild = Response.status(Response.Status.BAD_REQUEST);
return rBuild.type(MediaType.TEXT_PLAIN)
.entity(results.get("ErrorDescription"))
.build();
} else {
File responseData = decodeBase64(((String) results.get("Base64String")).replace("\n", ""));
Response.ResponseBuilder rBuild = Response.ok(responseData, "application/pdf");
return rBuild.build();
}
}
【问题讨论】:
-
发生错误时,您不能将响应重定向到另一个 URL 位置吗?
-
我也对此进行了调查。 (sendRedirect(request, response, targetUrl)) 但我不确定最好的方法是获取请求/响应对象。
标签: java spring rest spring-mvc jax-rs