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 and flush() 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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
pol
pol
3 years ago

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");

Back to top button