Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a servlet from Java code

Tags:

java

servlets

I want to call servlet with some parameters and receive a response. The code is written in Java. What is the best (cleanest) way to do that?

Also, can i call a servlet and continue with the code withoud waiting the servlet to finish (close the connection and "forget about it")?

like image 729
Erik Sapir Avatar asked May 03 '11 07:05

Erik Sapir


2 Answers

Better use Apache HttpClient API for handling and communication with servlet

http://hc.apache.org/httpcomponents-client-ga/index.html

Features:

  1. Param are easy to pass and parse response.
  2. It allows even communicating thru Proxy
  3. Open source
  4. It also support Asyncronous and many more Please refer the above url.
like image 122
Pazhamalai G Avatar answered Sep 20 '22 11:09

Pazhamalai G


Example from here:

import java.net.*;
import java.io.*;

public class URLConnectionReader {
  public static void main(String[] args) throws Exception {
    URL yahoo = new URL("http://www.yahoo.com/");
    URLConnection yc = yahoo.openConnection();
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            yc.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);
    in.close();
  }
}

From your perspective, servlet is just an URL on some server. As for not waiting for a response - read about Java threads. But you cannot close the HTTP connection without waiting for a servlet to finish as this might cause a servlet to fail. Simply wait for the response in a separate thread and discard it if it doesn't matter.

like image 26
Tomasz Nurkiewicz Avatar answered Sep 21 '22 11:09

Tomasz Nurkiewicz