HTTP Post from a socket


Earlier on we already saw how to read from a Socket. This example shows how to do a HTTP POST. The HTTP post can take more data. Such as binary data.

This example can therefore be useful to post multiple documents to another program such as Apache Solr. Note that you also can do this with the UNIX / Linux cURL command

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Create a socket to the host
    String hostname = "";
    int port = 80;
    InetAddress addr = InetAddress.getByName(hostname);
    Socket socket = new Socket(addr, port);

    // Send header
    String path = "/servlet/SomeServlet";
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    wr.write("POST "+path+" HTTP/1.0rn");
    wr.write("Content-Length: "+data.length()+"rn");
    wr.write("Content-Type: application/x-www-form-urlencodedrn");

    // Send data

    // Get response
    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
} catch (Exception e) {


One thought on “HTTP Post from a socket”

  1. I just couldn’t depart your web site prior to suggesting that I actually enjoyed the standard info a person provide for your visitors? Is gonna be back often in order to check up on new posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.