6

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")?

James Kingsbery
  • 7,298
  • 2
  • 38
  • 67
Erik Sapir
  • 23,209
  • 28
  • 81
  • 141
  • You can spin off your request into a separate `Thread` if you want to continue with other parts of your application. See also: http://stackoverflow.com/questions/4349854/calling-a-servlet-from-a-java-application – Catchwa May 03 '11 at 07:13
  • "What is the best (cleanest) way to do that" what does *best* or *cleanest* mean. – Raedwald Jul 28 '14 at 12:28

4 Answers4

4

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Do i have to wait for a response (if the solution if to use a thread, than the answer is still yes - i have to wait for an answer). What about passing parameters to the servlet? do i have to bild the url by myself (using '?' and '&') or there is a cleaner way? – Erik Sapir May 03 '11 at 07:14
4

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.
Pazhamalai G
  • 154
  • 1
2

You could use Apache HttpClient Apache HttpClient

This also has Non-blocking I/O functionality available NIO extensions

Here's a Tutorial for the Apache HttpComponents.

You could also try Jetty or Async Http Client

Jon
  • 365
  • 2
  • 13
  • 1
    i really dislike people who downvote with no comment. Here's an upvote to balance the force. – Nico Jun 01 '12 at 15:41
0

For me this was the shortest and most useful tutorial about Apache HttpClient.

Gismo Ranas
  • 6,043
  • 3
  • 27
  • 39