我正在使用RESTEasy开发休息服务,该服务的目的是从POST请求中获取文本文件并解析它。我有两种方式:
@Path("/HTTPRequestWay")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String uploadFile2(
@HeaderParam("sourceSystem")String sourceSystem,
@HeaderParam("payloadType")String payloadType,
@Context HttpServletRequest request){
String payloadHTTP = "";
try {
payloadHTTP = getBody(request);
}catch (IOException e){
e.printStackTrace();
payloadHTTP = "error";
}
return payloadHTTP;
}
@Path("/InputStreamWay")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String uploadFile2(
@HeaderParam("sourceSystem")String sourceSystem,
@HeaderParam("payloadType")String payloadType,
InputStream payload){
String payloadInputStream = "none";
try {
payloadInputStream = IOUtils.toString(payload, "UTF-8");
}catch (IOException e){
e.printStackTrace();
payloadInputStream = "error";
}
finally{
IOUtils.closeQuietly(payload);
}
return payloadInputStream ;
}
public static String getBody(HttpServletRequest request) throws IOException {
String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
return body;
}
我试图用HttpServletRequest(获取正文)或在方法中放置一个参数(InputStream)来解析文件。我怀疑第二种情况为什么我的方法可以转换文件我发送在参数(InputStream有效载荷)? 它对我来说看起来很神奇为什么它的第二种方式起作用哪种更好?谢谢
答案 0 :(得分:1)
它不是魔术,它只是从InputStream
注入HttpServletRequest
。在docs获取战利品。
Resteasy可以自动编组和解组几个不同的邮件正文。
其中一个是java.io.InputStream
。