0

I'm starting to learn about servlets, I know that if I deploy the servlet on the server then I can access that servlet using a get request via browser. now the question I have is that is it possible to access the same servlet from a java desktop application(Using sockets.)?
here is my client side code:

public class SocketClient {
    public static void main(String[] args) throws IOException {
        Socket myClient;
        Scanner reader;

        myClient = new Socket("http://localhost:8080/HelloWorld/MyFirstServlet", 8080);
        reader = new Scanner(myClient.getInputStream());
        System.out.println(reader.nextLine());
    }
}
Stefano Sanfilippo
  • 29,175
  • 7
  • 71
  • 78
Sina Barghidarian
  • 370
  • 1
  • 3
  • 17

2 Answers2

1

Surely you can. But you do not have to open socket. You have to create HTTP connection instead. Take a look on the following discussion for details:

How do I do a HTTP GET in Java?

If you need to use other HTTP method google something like: "how to make HTTP METHOD request in java" where METHOD is GET, POST, DELETE, HEAD, OPTIONS etc.

Community
  • 1
  • 1
AlexR
  • 109,181
  • 14
  • 116
  • 194
1

Yes, you can. A browser is just a computer program. It uses sockets to communicate with the server. You could write a program that also used sockets to communicate with the server. Your program would have to use the same communication protocol as the a browser: HTTP.

In fact, writing programs that communicate with an HTTP server is so common that Java provides an API for this (look for questions on SO about using java.net.URLConnection), and there are application frameworks built on top of those basics to make it even easier (such as RestTemplate of Spring).

Community
  • 1
  • 1
Raedwald
  • 40,290
  • 35
  • 127
  • 207