Socket
Send HTTP POST request with Socket
This is an example of how to send an HTTP POST request with a Socket. A socket is an endpoint for communication between two machines. Sending an HTTP POST request using a Socket implies that you should:
- Get the InetAddress of a specified host, using the host’s name, with
getByName(String host)API method of InetAddress. - Create a new Socket and connect it to a specified port number at a specified IP address.
- Get the output stream of the socket, using
getOutputStream()API method of Socket. - Create an OutputStreamWriter with the socket ouputstream that uses the given UTF-8 encoder.
- Create a BufferedWriter that uses a default-sized output buffer.
- Use
write(String str)API method to send the headers and the parameters andflush()API method to flush the stream. - Get the socket input stream, using
getInputStream()API method of Socket. - Create a new BufferedReader, using a new InputStreamReader with the socket input stream.
- Use
readLine()API method to read the response. - Don’t forget to close both the BufferedWriter and the BufferedReader using the
close()API methods.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLEncoder;
public class SendHTTPPOSTRequestWithSocket {
public static void main(String[] args) {
try {
String params = URLEncoder.encode("param1", "UTF-8")
+ "=" + URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8")
+ "=" + URLEncoder.encode("value2", "UTF-8");
String hostname = "mysite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/myapp";
// Send headers
BufferedWriter wr =
new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("POST "+path+" HTTP/1.0rn");
wr.write("Content-Length: "+params.length()+"rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This was an example of how to send an HTTP POST request using a Socket in Java.

And what should come in response to this request? And what are these lines for:
wr.write("POST "+path+" HTTP/1.0rn");wr.write("Content-Length: "+params.length()+"rn");wr.write("Content-Type: application/x-www-form-urlencodedrn");wr.write("rn");