I'm developing a rest service using RESTEasy, the aim of the service is to get a text file from the POST request and parse it. I have done it in 2 ways:
@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;
}
i was trying to parse the file either with the HttpServletRequest (getting the body) or putting a parameter in the method (InputStream) .My doubt is about this second case why my method can convert the file i'm sending in the parameter (InputStream payload)? It looks like magic to me why does it works the second way and which is the better? Thanks