簡體   English   中英

在J2ME中從servlet檢索響應時遇到問題

[英]Having problems retrieving response from a servlet in J2ME

我試圖使用下面的代碼檢索從servlet到midlet的響應

public String receiveData() {
        HttpConnection connection = null;
        String url = "http://localhost:8084/MCastServer/Create";
        DataInputStream is = null;
        OutputStream os = null;
        StringBuffer stringBuffer = new StringBuffer();
        String res = null;
        try {
            connection = (HttpConnection) Connector.open(url);
            connection.setRequestMethod(HttpConnection.GET);
            connection.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
            connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0");
            connection.setRequestProperty("Content-Language", "en-CA");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            os = connection.openOutputStream();
            is = connection.openDataInputStream();
            System.out.println(url);
            int ch = 0;
            while ((ch = is.read()) == -1) {
                stringBuffer.append((char) ch);
                System.out.println(stringBuffer);
            }
            res = stringBuffer.toString();
            System.out.println(res);
            //ByteArrayOutputStream bos = new ByteArrayOutputStream();
        } catch (Exception e) {
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
                if (connection != null) {
                    connection.close();

                }
                //display.setCurrent(textBox);
            } catch (Exception e) {
            }

        }
        return res;
    }

但它不斷返回空輸出。 我已經搜索並嘗試了各種方法,但它仍然返回相同。 下面是我寫的Servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();

        String groupNames = "SELECT phone_group_name FROM phone_group_name";
        InteractToDB dbCall = new InteractToDB("org.postgresql.Driver");
        dbCall.connect("jdbc:postgresql://localhost:5432/mcast", "postgres", "mimi");
        out.print(dbCall.getNames());
        System.out.println(dbCall.getNames() + " call");
        try {

        } finally {
            out.close();
        }
    }

你有一個空的擋塊 - 這不是一個好主意。 您應該至少打印堆棧跟蹤。

我還認為將數據庫代碼放在servlet中是一個糟糕的主意。 我編寫了一個基於接口的POJO,在沒有servlet的情況下徹底測試代碼,然后在servlet中調用它的方法。 它將問題分解為較小的問題,並幫助您的單元測試工作。

為什么要為每個請求創建連接? 為什么不使用連接池來分攤創建連接的成本?

為什么要在課堂上以純文本形式對您的信息進行硬連接? 如果dbCall為null會發生什么? 如果SQLException怎么辦?

我看這個代碼越多,它就越糟糕。 我現在最好停下來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM