Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read post request values HttpHandler

Tags:

java

http

I'm writing a little Java app which implements an http service that receives http post commands from a client.

The class I'm using to implement all of this is HttpHandler and HttpServer in the com.sun.net. package.

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.

I'm looking to parse text post values and uploaded files.

like image 953
Haim Bender Avatar asked Aug 04 '10 20:08

Haim Bender


2 Answers

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);
}
like image 104
Maurice Perry Avatar answered Sep 30 '22 17:09

Maurice Perry


An alternative would be using HttpService from HttpCore.

There is a Basic HTTP server example in the documentation

like image 44
fglez Avatar answered Sep 30 '22 16:09

fglez