gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:53:12 24 4
gpt4 key购买 nike

我正在使用 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)中放入参数来解析文件。我的疑问是第二种情况,为什么我的方法可以转换我在参数(输入流负载)?对我来说这看起来很神奇,为什么它会以第二种方式工作,哪种方式更好?谢谢

最佳答案

这并不神奇,它只是从 HttpServletRequest 注入(inject) InputStream。抢夺 docs .

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

其中之一是java.io.InputStream

关于java - 使用 POST 请求将文件发送到 REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37463943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com