How to call a servlet from Java code

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

Also, can I invoke the servlet and continue with the code, waiting for the servlet to complete (close the connection and forget about it)?

+6
source share
4 answers

Better use the Apache HttpClient API to process and communicate with servlets

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

Features:

  • Couples can easily convey and analyze the answer.
  • This allows you to even exchange through a proxy.
  • Open source
  • It also supports Asyncronous and more. Please refer to the address above.
+4
source

An 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 point of view, a servlet is just a URL on some server. As for not expecting an answer, read about Java threads. But you cannot close the HTTP connection without waiting for the servlet to complete, as this may cause the servlet to fail. Just wait for the response in a separate thread and discard it if it does not matter.

+4
source

You can use Apache HttpClient Apache HttpClient

It also has NIO extension non-blocking I / O functionality.

Here's a tutorial for Apache HttpComponents.

You can also try Jetty or Async Http Client

+2
source

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

0
source

Source: https://habr.com/ru/post/887170/


All Articles