Aidan
Aidan

Reputation: 225

Retrieving POST data using Java

I'm trying to make a Java server that can accept and return data using POST. So far I have been trying to use nameValuePairs (although another method be fine) and have the server accepting connections, and accepting the HTTP header, but from here I cannot fathom how to get any attached data. The following code prints out the header and sends a 100 response once the client expects it - but how do I get the data from the message?

        while(true){
        inputLine = clientInput.readLine();
        System.out.println("client-msg: " + inputLine);
        if("Expect:".equals(inputLine.split(" ")[0])){
            sendResponse(100, "Continue");
            break;
        }

Here is what the (android java) client is sending, I'm looking to get the name pair out on the server side

            ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("field", "data here"));
        UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(
                postParams);
        request.setEntity(uefe);
        HttpResponse response = client.execute(request);

This is probably fairly simple but I couldn't seem to find any non PHP tutorials for POST.

Upvotes: 1

Views: 2952

Answers (3)

Cratylus
Cratylus

Reputation: 54094

From your code my understanding is that your approach is to open a server socket and read-in line by line.
What you are supposed to do here is find the header "Content-length".
This header shows the size of the body carried in the POST request.
From your question, I think that you are receiving a POST request similar to the following:

POST /path HTTP/1.1
From: myUser
User-Agent: java
Content-Length: 32

name1=value1&name2=value2

Note the extra new line (i.e. '\n') between the HTTP headers and the actual data.
You should use the content length and the fact that you already know where are the data related to the HTTP headers, inside the HTTP request to parse it and extract the values of interest.
So that you eventually get the name1=value1&name2=value2.
If you just want to do it as an exercise, go ahead.
It is more complex than you think and you have to look to the RFC a bit.
For example I do not remember it is actually a '\n' or a '\r\n' or something similar.
Also I do not remember if content-length will be always there (for example in the responses it can be missing and the http server may send the response in encoded chunks).
If you need to do it though seriously, then you should use an http server implementation.
There is already an http server implementation shipped in java or you can use apache's.
Do not try to re-invent the wheel, unless you are doing for education or fun.

Upvotes: 1

nrobey
nrobey

Reputation: 715

From context, it looks as though you should look into using Servlets, and run it on a lightweight servlet platform like Jetty.

You must override the doPost method on the Servlet class. On the HttpServletResponse object, use getParameterNames() to get all of the uploaded parameter names, and getParameter() to get their values.

Upvotes: 0

carson
carson

Reputation: 5759

If you really need to do this by hand you should read the HTTP RFC because it is potentially even more complicated than what you are trying to do now. If what you really want is a way to embed a small Java web server into something check out Jetty. It is really easy to embed Jetty into other apps.

It should be as easy as:

public class SimpleServletContext
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        context.addServlet(new ServletHolder(new PostServlet()),"/*");

        server.start();
        server.join();
    }
}

public class PostServlet extends HttpServlet
{
    public PostServlet()
    { 
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // do something with the posted data
    }
}

Upvotes: 2

Related Questions