Http Client server application GET/POST in Java Example

 
Welcome, Visitor. Subscribe to our RSS Feed and consider adding this article/site to your favorite social bookmark site if you find it useful. Thank you!

This tutorial will cover a Http Client server application GET/POST in Java Example. The goal of this tutorial is to create a GUI application that connects to web and shows addition of two numbers. This is tutorial part one for creating the server side application. Next part will show the GUI creation. and In this tutorial, I am using NetBeans IDE and Glassfish Server. Focus of this application are following:

  • Create Web application that can add two numbers
  • Create Java application that can take input from webserver

 

First part is to create Web server application for our client server application. Create a new web application from File > New Project > Java Web and select Web application. Then click Next and type in Project name.

Now Click Next and select Glassfish Server and click finish

You will see that a new web application project have been created. Do a right-click on the project and click on run. You will see that your configured browser have started a localhost link using Glassfish Server. My application is showing http://localhost:8080/ClientServerWeb/  according to above project settings. If the server started and localhost url is showing demo web page, then we are in right track. Next step is to start coding out server side application that can return addition of two number using http.

Http Client server application GET/POST in Java Example


Do a right-click on the project and click on New>Servlet . Type in class name as MyServlet Package name as com.web.server then click next and Finish. You will see some auto generated code for your class. At first check that java package name and imports looks like following. Or else import the missing ones. :

package com.web.server;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.Double.sum;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Now delete any following from auto generated code:

            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet test</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet test at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");

Add following piece of code at the place of deleted code:

      
 
            String number1param = request.getParameter("num1");
            String number2param = request.getParameter("num2");
// check that number1param and number2param  is not null and continue
            if (number1param != null && number2param != null) {

                double number1 = Double.parseDouble(number1param);
                double number2 = Double.parseDouble(number2param);
                double sum = number1 + number2;

                out.print("The sum of two number is : " + sum);

            } else {
                out.print("Enter two parametere num1 and num2");
            }
        } finally {
            out.close();

Here we declared number1param and number2param to get the value of variable num1 and num1. Then we added a condition to check the that number1param and number2param is not null and continue. Then we did simple mathematical calculation of the numbers and printed printed the output.

At this point your code will look like the code below:

/*
Http Client server application GET/POST in Java Example 
By Garnel K at www.bytetips.com
 */
package com.web.server;

import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Garnel K
 */
@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            String number1param = request.getParameter("num1");
            String number2param = request.getParameter("num2");

            if (number1param != null && number2param != null) {

                double number1 = Double.parseDouble(number1param);
                double number2 = Double.parseDouble(number2param);
                double sum = number1 + number2;

                out.print("The sum of two number is : " + sum);

            } else {
                out.print("Enter two parametere num1 and num2");
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

 
Now right click on the file and click on Run file and type in /MyServlet?num1=1&num2=2 and click OK.

You will see a url like this http://localhost:8080/ClientServerWeb/MyServlet?num1=1&num2=2 and the web page output like The sum of two number is : 3.0 You have successfully created a server side web application that takes two parameter and shows the result of addition. Next tutorial will show how to connect GUI application to provide input parameter.

Tags for the article:

    java get post

, , ,

No comments yet.

Leave a Reply

14 + 17 =