我正在尝试解析HTTP POST请求,以便检索使用HTML表单发送的文件。
这是表格:
<form action="http://127.0.0.1:8081" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileControl" />
<input type="submit" />
</form>
因为POST请求与此类似:
POST <URL> HTTP/1.1
<HEADERS>
[BLANK LINE]
---------<BOUNDARY>
<HEADERS>
[BLANK LINE]
<file content>
-----------<BOUNDARY>
我认为解析我在套接字上收到的内容是相关的。
首先,我用
读到文件的开头BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
in.readLine();
然后,保存文件,这就是我要做的事情:
FileOutputStream outputStream = new FileOutputStream(new File("/tmp/test"));
while ((read = clientSocket.getInputStream().read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
outputStream.flush();
}
问题是我不再通过我的BufferedReader阅读了,而{I} {<1}}
中没有任何内容如何通过POST请求保存文件发送?我不想使用任何webserver,也不想使用任何库/框架,只使用纯Java。 如果不清楚,我会编辑这篇文章。 提前谢谢。
答案 0 :(得分:0)
public HttpRequest init_request(String request_str) {
try {
SessionInputBufferImpl sessionInputBuffer = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 2048);
sessionInputBuffer.bind(new ByteArrayInputStream(request_str.getBytes(Consts.ASCII)));
DefaultHttpRequestParser requestParser = new DefaultHttpRequestParser(sessionInputBuffer);
HttpRequest request = requestParser.parse();
// Solve post request entity bug (always returns null)
if(request instanceof HttpEntityEnclosingRequest){
HttpEntityEnclosingRequest ereq = (HttpEntityEnclosingRequest) request;
ContentLengthStrategy contentLengthStrategy = StrictContentLengthStrategy.INSTANCE;
long len = contentLengthStrategy.determineLength(request);
InputStream contentStream = null;
if (len == ContentLengthStrategy.CHUNKED) {
contentStream = new ChunkedInputStream(sessionInputBuffer);
} else if (len == ContentLengthStrategy.IDENTITY) {
contentStream = new IdentityInputStream(sessionInputBuffer);
} else {
contentStream = new ContentLengthInputStream(sessionInputBuffer, len);
}
BasicHttpEntity ent = new BasicHttpEntity();
ent.setContent(contentStream);
ereq.setEntity(ent);
}
return request;
} catch (Exception e) {
SLogger.error("Unable to parse request", e);
return null;
}
}
答案 1 :(得分:-1)
使用Apache httpcomponents / httpclient库生成并发送post请求。任何其他事情都是徒劳无功的。
请参阅https://hc.apache.org/httpcomponents-client-ga/quickstart.html