使用 POST 请求将文件发送到 REST 服务

Sending file to REST Service with POST Request

我正在使用 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 有效负载)中? 对我来说这看起来很神奇,为什么它以第二种方式起作用,哪种更好?谢谢

这不是魔术,它只是从 HttpServletRequest 注入 InputStream。在 docs.

抢劫

Resteasy can automatically marshal and unmarshal a few different message bodies.

其中之一是java.io.InputStream