Search code examples
javahttpserver

HTTPServer Post parameters


Am writing a service using the HTTPServer provided by com.sun.net.httpserver.HttpServer package. I need to send some sizable data as a byte stream to this service (say a million integers).

I have almost searched all the examples available, all point to sending a small GET request in the URL. I need to know how to send the data as a POST request. Also is there any limit on the data that can be sent?


Solution

  • Rather than persistent URL connection in the answer above, I would recommend using Apache HTTPClient libraries (if you are not using Spring for applet-servlet communication)

    http://hc.apache.org/httpclient-3.x/

    In this you can build a client and send a serialized object (for instance serialised to JSON string: https://code.google.com/p/google-gson/ ) as POST request over HTTP to your server:

    public HttpResponse sendStuff (args) {
        HttpPost post = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();
    
            post = new HttpPost(servletUrl);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(<nameString>, <valueString>));
    
            post.setEntity(new UrlEncodedFormEntity(params));
    
            HttpResponse response = client.execute(post);
            response.getStatusLine().getStatusCode();
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    

    However Spring saves you a lot of time and hassle so I would recommend to check it out