Swing與Servlet通訊簡單示例

有系統要基於原有的Web項目,開發客戶端,由原有的Servlet提供請求處理。
技術關鍵詞:Java,Servlet,Swing
這顯然要用到Java網絡編程,經過程序來模擬請求。
假設Servlet簡化爲以下代碼:
                response.setContentType( "text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                 try {
                        out.println( "你好");
                } finally {
                        out.close();
                }
客戶端簡化爲一個按鈕和一個單行文本框。點擊按鈕則請求Servlet,並將響應文本顯示到文本框中:
private void btGetActionPerformed(java.awt.event.ActionEvent evt) {                                                                            
        String urlString = tfURL.getText();
        StringBuffer document = new StringBuffer();

         try {
                URL url = new URL(urlString);
                URLConnection conn = url.openConnection();
                BufferedReader reader = new BufferedReader( new InputStreamReader(
                                conn.getInputStream(), "UTF-8"));
                String line = null;
                 while ((line = reader.readLine()) != null) {
                        document.append(line + "\r\n");
                }
                reader.close();
        } catch (MalformedURLException e) {
                System.out.println( "不能鏈接URL: " + urlString);
        } catch (IOException e) {
                System.out.println( "響應操做失敗: " + urlString);
        }
         this.tfMessage.setText(document.toString());
}
注意其中
new InputStreamReader(conn.getInputStream(), "UTF-8")
表示響應流採用UTF-8解析,這樣就與Servlet編碼一致起來,就不會出現亂碼結果。英語系程序員真幸福,歷來不用考慮編碼問題,羨慕ing......
相關文章
相關標籤/搜索