Difference between GET and POST method

Difference between GET and POST method

GET and POST are two of the most commonly used HTTP methods. They serve different purposes and have distinct characteristics.

GET Method

  • Purpose: Retrieve data from a server.
  • Parameters: Sent in the URL query string.
  • Visibility: Parameters are visible in the URL, making GET requests less secure for sensitive data.
  • Caching: GET requests can be cached by browsers and intermediate servers.
  • Idempotency: GET requests are idempotent, meaning multiple identical requests should have the same effect as a single request.
  • Use Case: Suitable for fetching data, like loading a webpage or retrieving search results.

POST Method

  • Purpose: Send data to the server to create or update resources.
  • Parameters: Sent in the request body, not visible in the URL.
  • Visibility: Parameters are hidden from the URL, making POST requests more secure for sensitive data.
  • Caching: POST requests are not cached by default.
  • Idempotency: POST requests are not idempotent, meaning multiple identical requests can have different effects.
  • Use Case: Suitable for submitting form data, uploading files, or any action that changes server state.

 GET and POST method

Let’s create a Java example demonstrating both GET and POST method requests using the HttpURLConnection class.

Server-Side Code
Server-Side Code
1. Create a Servlet that handles both GET and POST requests:

java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String param = request.getParameter("param");
        response.getWriter().write("GET request received. Param: " + param);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String param = request.getParameter("param");
        response.getWriter().write("POST request received. Param: " + param);
    }
}


Java Client for GET Request:

java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpGetExample {
    public static void main(String[] args) {
        try {
            String param = "exampleParam";
            URL url = new URL("http://localhost:8080/your_webapp/example?param=" + param);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            System.out.println("GET Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                System.out.println("GET Response: " + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Java Client for POST Request:

java
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPostExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/your_webapp/example");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            String param = "param=exampleParam";
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(param.getBytes());
            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();
            System.out.println("POST Response Code: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                System.out.println("POST Response: " + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation GET and POST method

Server-Side Servlet

  • The servlet listens at the /example URL.
  • It handles both GET and POST requests by reading the param parameter from the request and writing a response.

Client-Side Code

  • GET Request: The client sets up an HttpURLConnection to the servlet’s URL with the parameter in the query string. It reads and prints the server’s response.
  • POST Request: The client sets up an HttpURLConnection to the servlet’s URL. It sends the parameter in the request body, then reads and prints the server’s response.

Homepage

Readmore