将Swing应用程序(客户端)连接到servlet

时间:2013-05-13 10:43:22

标签: java swing servlets executable-jar login-control

我必须在客户端检查我的swing应用程序中的登录凭据,该凭据由可执行jar文件调用。填写完详细信息后,它会检入数据库中的servlet。我的servlet运行正常。

如何将Swing应用程序(客户端)连接到servlet?

2 个答案:

答案 0 :(得分:1)

请看看@这篇文章

How to call the Servlet from Java Swing login page using HttpClient in apache?

可能有助于解决..

欢呼声!!!

答案 1 :(得分:1)

您可以使用HttpURLConnection从摇摆到您的服务器发出http请求。

示例:

HttpURLConnection connection;


try {

      String urlParameters = "username="+URLEncoder.encode(username,"UTF-8") 
                    +"&password="+URLEncoder.encode(password,"UTF-8");
      //Create connection

      URL url=new URL("your servlet url goes here");
      connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", 
           "application/x-www-form-urlencoded");

      connection.setRequestProperty("Content-Length", "" + 
               Integer.toString(urlParameters.getBytes().length));
      connection.setRequestProperty("Content-Language", "en-US");  

      connection.setUseCaches (false);
      connection.setDoInput(true);
      connection.setDoOutput(true);

      //Send request
      DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
      wr.writeBytes (urlParameters);
      wr.flush ();
      wr.close ();

      //Get Response    
      InputStream is = connection.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      while((line = rd.readLine()) != null) {
        // read response from your servlet
      }
      rd.close();


    } catch (Exception e) {

      e.printStackTrace();


    } finally {

      if(connection != null) {
        connection.disconnect(); 
      }
    }