简体   繁体   中英

Receive POST Data equivalent in Java

I've got the following python code which receives POST Data and writes it into a file.

def do_POST(self):
    content_length = self.headers['content-length']
    content = self.rfile.read(int(content_length))
    with open("filename.txt", 'w') as f:
        f.write(content.decode())
    self.send_response(200)

What's the equivalent in Java? I'm using NanoHTTPD as a HTTP Server but for some reason, my Java Application is only receiving the POST Request with headers without data while the python application is receiving the whole set of data.

UPDATE (Java Code):

 public Response serve(IHTTPSession session)
  {
    Method method = session.getMethod();
    String uri = session.getUri();
    LOG.info(method + " '" + uri + "' ");

    Map<String, String> headers = session.getHeaders();

    String cl = headers.get("Content-Length");
    int contentLength = 0

    if (null != cl)
    {
        contentLength = Integer.parseInt(cl);
    }

    InputStream is = session.getInputStream();

    int nRead;
    byte[] data = new byte[contentLength];

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try
    {
        LOG.info("Start Read Data");
        while ((nRead = is.read(data, 0, data.length)) != -1)
        {
            LOG.info("Read Data: " + nRead);
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        LOG.info("Result: " + new String(buffer.toByteArray(), "UTF-8"));
    }
    catch (IOException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
 return newFixedLengthResponse("");
}

Your contentLength variable is always zero because NanoHTTPD converts all headers into lower case before storing them into a Map. So to get the Content-Length header, you should use:

String cl = headers.get("content-length");
int contentLength = 0

if (null != cl)
{
    contentLength = Integer.parseInt(cl);
}

Alternatively, IHTTPSession provides a method parseBody(Map<String, String> map) . If the content type is application/x-www-form-urlencoded , the body will be decoded into the map. Otherwise (other content type), the map will contain a single key "postData" which is the request's body.

Map<String, String> requestBody = new HashMap<String, String>();
try {
    session.parseBody(requestBody);
} catch (Exception e) {
    e.printStackTrace();
}
String parameters = null;
if (requestBody.containsKey("postData")) {
    parameters = requestBody.get("postData");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM