Learn how to make HTTP request using plan Java Socket

Learn how to make HTTP request using plan Java Socket


0






Rahul Kumar (@rahul)

Learning network programming is always a fun. Whether you're a novice or seasoned developer, let's learn how to make HTTP requests using plain Java Sockets!

Prerequisites

There are a few recommendations for you to learn before going ahead with this article. If you already know them then you can move ahead. 

What is HTTP?

Hypertext transfer protocol (HTTP) is an application layer protocol that works on top of other network protocols like TCP. HTTP is a text-based protocol which means you don’t need to encode information into binary format before you send then over the wire. You can understand the reason why HTTP is a text-based protocol.

HTTP works on the client/server model, where browsers are the usual clients. The client makes requests to the web server using one of the available HTTP methods and the server responds accordingly. 

What is TCP?

The transmission control protocol (TCP) is one of the main protocols of the Internet protocol suite. It is a transport layer protocol that facilitates the transmission of packets from the source to the destination. 

TCP is a stream-oriented protocol as it allows the sender to send the data in the form of a stream of bytes and also allows the receiver to accept the data in the form of a stream of bytes. It means that TCP deals with binary data and anything can be sent over TCP if it's binary. 




A typical HTTP request consists of the HTTP method, URL, HTTP version and Host.

HTTP Request

      GET / HTTP/1.1
Host: localhost
    

In the above snippet, GET is the HTTP method, / is the URL, HTTP/1.1 is the HTTP version and localhost is the host. 

Since HTTP is a plain text protocol, it only deals with text. We can send the above text over the network to any server. The receiving server must know rules of the HTTP protocol to parse the request, understand the request, process the request and respond accordingly. 

Learn how can we use Java to send HTTP requests

We can use TCP protocol in java to send HTTP request to the server. Let's starting coding to send HTTP request. 

TcpHttp.java

      import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TcpHttp {
    public static void main(String[] args) throws IOException {
        String GET_REQUEST = "GET / HTTP/1.1\r\nHost:localhost\r\n\r\n";
        Socket socket = new Socket("localhost", 8080);
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
    }
}

    

In the above code, we have created a Socket object which is bound to the localhost host and port 8080. localhost is the host where HTTP server is running. We have also created two other I/O object of InputStream and OutputStream respectively.  

InputStream is used to read from the Socket and OutputStream is used to write on to the Socket. GET_REQUEST variable is holding the content for HTTP request, similar to what we saw in What is TCP? section. 

Now, we have two things remaining to do. Send data to the server. Read data from the server. 

Write Data on to the Socket

      try {
    os.write(GET_REQUEST.getBytes());
    socket.shutdownOutput();
} catch (IOException e) {
    throw new RuntimeException(e);
}
    

OutputStream has a write method which takes a byte or array of byte. shutdownOutput() methods indicates that OutputStream has been closed and there is no more data to write. 

Read Data from Socket

      int b;
while (true) {
    try {
        if ((b = is.read()) == -1) {
            break;
        }
        System.out.print((char) b);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
    

InputStream has a read method which read one byte from the Socket at a time. read method returns -1 where there is no data present on the Socket to read. In the above code snippet we are reading bytes from Socket in a while loop and printing data over terminal. We converting byte to character, so that we can read them from the terminal. 

Full Code Example of sending plain HTTP request using Java

Code to send HTTP request

TcpHttp.java

      import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TcpServer {
  public static void main(String[] args) throws IOException {
    String GET_REQUEST = "GET / HTTP/1.1\r\nHost:localhost\r\n\r\n";
    Socket socket = new Socket("localhost", 8080);
    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();

    try {
      os.write(GET_REQUEST.getBytes());
      socket.shutdownOutput();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    int b;
    while (true) {
      try {
        if ((b = is.read()) == -1) {
          break;
        }
        System.out.print((char) b);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
}

    

Creating a Server

I am using Spring Boot to create a server that will receive the request and respond with some string. Don’t worry if you don’t know about spring boot, you can spring initializr to quickly set up a spring boot server.  

This server will listen on path / and respond with a string message.  

HTTP Server

      import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller {
  @GetMapping("/")
  public String hello() {
    String message = """
Hello, TCP
""";
    return message;
  }
}

    

Now, we have created a server that will listen on the specified port(8080 by default) and can accept HTTP requests.

Running TcpHttp.java

Output of TcpHttp.java

      HTTP/1.1 200 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: text/plain;charset=UTF-8
Content-Length: 11
Date: Sun, 04 Feb 2024 10:46:36 GMT

Hello, TCP
    

Wow 😯 😮 ! We have just sent plain HTTP request using Java Sockets!

Wait!! Why there are extra output that Hello, TCP

You must have noticed that we are using spring boot server, which uses tomcat under the hood. These are the headers sent by the server itself apart from user defined controller response.  

Summary

This article provides a comprehensive overview of HTTP, TCP, and Java network programming. HTTP, a text-based application layer protocol, operates on top of TCP, facilitating communication between clients and servers. It covers the structure of HTTP requests and introduces the concept of TCP's stream-oriented data transmission and how to send plain HTTP request using Java Sockets. 

Add a thoughtful comment...

✨ Explore more tech insights and coding wonders with @dsabyte! Your journey in innovation has just begun. Keep learning, keep sharing, and let's continue to code a brighter future together. Happy exploring! 🚀❤️

  • #java
  • #http
  • #tcp
  • #sockets
  • #server
  • #raw

Subscribe to our newsletter.

Join the "News Later" community by entering your email. It's quick, it's easy, and it's your key to unlocking future tech revelations.

Weekly Updates

Every week, we curate and deliver a collection of articles, blogs and chapters directly to your inbox. Stay informed, stay inspired, and stay ahead in the fast-paced world of technology.

No spam

Rest assured, we won't clutter your inbox with unnecessary emails. No spam, only meaningful insights, and valuable content designed to elevate your tech experience.

© 2024 @dsabyte. All rights reserved