How to call and pass the parameters to the Servlet

2019-07-15 20:41发布

问题:

This question already has an answer here:

  • How to send HTTP request in java? [duplicate] 9 answers
  • How to use java.net.URLConnection to fire and handle HTTP requests 11 answers

In my Swing application I need to pass the parameters to the servlets using the login page to authenticate the user.

In the web application we can do this by using Ajax and JavaScript.

But, how can I achieve this in my Swing application? My team leader asked me to go with HTTP client in Apache.

Please help me to do this.

回答1:

Your details are pretty scratchy, but from what I understand and your team lead says the right thing for the job is a HTTP POST, and this is better achieved with httpcomponents from apache.

Some sample code might look like:

 HttpClient client = new DefaultHttpClient();
 HttpPost post = new HttpPost(urlAsString);

 HttpResponse rsp = null;

    try {
        rsp = client.execute(post);
    } catch (IOException e) {
        //ha ha
    } finally {
        //close stuff
    }

and probably you will need to fetch some token from the response in order to make later request as logged in, but this is a implementation detail.

A pretty good example can be found here: http://www.vogella.com/articles/ApacheHttpClient/article.html

This is from the top of my head, hope it helps.



回答2:

You have to create HTTP request. The HTTP method depends on your servlet. To create basic HTTP request you should use HttpUrlConnection. If you need something more complex take a look on Apache HttpClient.



回答3:

As your team leader suggested, you can use the HTTP Client to issue a HTTP request to your servlet and passing in the desired parameters. See http://hc.apache.org/