gpt4 book ai didi

java - RESTlet:如何处理多部分/表单数据请求?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:18:56 26 4
gpt4 key购买 nike

当它是多部分/表单数据请求时,如何捕获传入的@Post 变量?

对于常规的 Post 请求,我会这样做:

@Post
public void postExample(Representation entity) throws Exception{
Form form = new Form(entity);
System.out.println(form.getFirstValue("something"));
}

但是因为它是一个 multipart/form-data 请求上面的输出 null

我是 Java 新手,所以请保持温柔:)

PS:我对处理传入的文件不感兴趣,只对文本字段感兴趣。

最佳答案

这是我的一种方法 (ReSTLet 2.0) 的粘贴。这里我有一个表单,包括一个文件上传和其他字段,因此它相当完整:

@Post
public Representation createTransaction(Representation entity) {
Representation rep = null;
if (entity != null) {
if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
// 1/ Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000240);

// 2/ Create a new file upload handler
RestletFileUpload upload = new RestletFileUpload(factory);
List<FileItem> items;
try {
// 3/ Request is parsed by the handler which generates a list of FileItems
items = upload.parseRequest(getRequest());

Map<String, String> props = new HashMap<String, String>();
File file = null;
String filename = null;

for (final Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
FileItem fi = it.next();
String name = fi.getName();
if (name == null) {
props.put(fi.getFieldName(), new String(fi.get(), "UTF-8"));
} else {
String tempDir = System.getProperty("java.io.tmpdir");
file = new File(tempDir + File.separator + "file.txt");
filename = name;
fi.getInputStream();
fi.write(file);
}
}

// [...] my processing code

String redirectUrl = ...; // address of newly created resource
getResponse().redirectSeeOther(redirectUrl);
} catch (Exception e) {
// The message of all thrown exception is sent back to
// client as simple plain text
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
e.printStackTrace();
rep = new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN);
}
} else {
// other format != multipart form data
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
rep = new StringRepresentation("Multipart/form-data required", MediaType.TEXT_PLAIN);
}
} else {
// POST request with no entity.
getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
rep = new StringRepresentation("Error", MediaType.TEXT_PLAIN);
}

return rep;
}

我最终会将其重构为更通用的东西,但这就是我现在所拥有的。

关于java - RESTlet:如何处理多部分/表单数据请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/996819/

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