我正在開發一個使用RESTEasy的休息服務,該服務的目標是從POST請求獲取文本文件並解析它。我已經在兩個方面做到了:使用POST請求發送文件到REST服務
@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有效載荷)發送的文件? 它對我來說看起來很神奇,爲什麼它會以第二種方式工作,哪個更好?謝謝
檢查http://stackoverflow.com/questions/24890675/file-upload-using-rest-api-in-java –