读取帖子请求值HttpHandler [英] read post request values HttpHandler
问题描述
我正在编写一个小型Java应用程序,它实现了一个从客户端接收http post命令的http服务。
I'm writing a little Java app which implements an http service that receives http post commands from a client.
我用来实现所有的这是com.sun.net中的HttpHandler和HttpServer。 package。
The class I'm using to implement all of this is HttpHandler and HttpServer in the com.sun.net. package.
现在我正在实现一个处理请求的句柄(HttpExchange交换)函数,我正在读取请求收到的帖子值,因为只有通过HttpExchange.getResponseBody()才能访问这些值,这只是一个输出流。
Now I'm implementing an handle(HttpExchange exchange) function which handles the request, and I'm having truble reading the post values received by the request because the only access that I have to these values is via HttpExchange.getResponseBody() which is just an output stream.
我正在寻找解析txt帖子值和上传文件。
I'm looking to parse txt post values and uploaded files.
请帮忙。
谢谢。
推荐答案
我编写了处理项目多部分请求的类 Sceye -Fi ,一个HTTP服务器,它使用java 6附带的 com.sun.net.httpserver
类来接收来自 Eye-Fi 卡。
I have written classes that process multipart requests for my project Sceye-Fi, an HTTP server that uses the com.sun.net.httpserver
classes that come with java 6, to receive photo uploads from an Eye-Fi card.
这有助于文件上传(多部分帖子) )。
This can help with file uploads (multipart posts).
对于非多部分的帖子,您需要执行以下操作:
For a non-multipart post, you would need to do something like this:
// determine encoding
Headers reqHeaders = exchange.getRequestHeaders();
String contentType = reqHeaders.getFirst("Content-Type");
String encoding = "ISO-8859-1";
if (contentType != null) {
Map<String,String> parms = ValueParser.parse(contentType);
if (parms.containsKey("charset")) {
encoding = parms.get("charset");
}
}
// read the query string from the request body
String qry;
InputStream in = exchange.getRequestBody();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte buf[] = new byte[4096];
for (int n = in.read(buf); n > 0; n = in.read(buf)) {
out.write(buf, 0, n);
}
qry = new String(out.toByteArray(), encoding);
} finally {
in.close();
}
// parse the query
Map<String,List<String>> parms = new HashMap<String,List<String>>();
String defs[] = qry.split("[&]");
for (String def: defs) {
int ix = def.indexOf('=');
String name;
String value;
if (ix < 0) {
name = URLDecoder.decode(def, encoding);
value = "";
} else {
name = URLDecoder.decode(def.substring(0, ix), encoding);
value = URLDecoder.decode(def.substring(ix+1), encoding);
}
List<String> list = parms.get(name);
if (list == null) {
list = new ArrayList<String>();
parms.put(name, list);
}
list.add(value);
}
这篇关于读取帖子请求值HttpHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!