从servlet到Midlet(J2ME)检索图像

时间:2012-04-07 15:48:52

标签: servlets netbeans java-me midlet

这是我目前的Midlet

 if (display.getCurrent() == mainform) {

            selectedparam = activity.getString(activity.getSelectedIndex());

            url = "http://localhost:8080/TOMCATServer/RetrieveServlet?";
            parameter = "activity=" + selectedparam;



            System.out.println(url + parameter);

            try {
                hc = (HttpConnection) Connector.open(url + parameter);
                hc.setRequestMethod(HttpConnection.POST);
                hc.setRequestProperty("CONTENT_TYPE", "application/x-www-from-urlencoded");
                hc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");

                out = hc.openOutputStream();
                byte[] postmsg = parameter.getBytes();
                for (int i = 0; i < postmsg.length; i++) {
                    out.write(postmsg[i]);
                }
                out.flush();
                in = hc.openInputStream();


                int ch;
                while ((ch = in.read()) != -1) {
                    b.append((char) ch);
                }

                String result = b.toString().trim();

                System.out.println(result);
                activitiesform.deleteAll();
                activitiesform.append(result);
                display.setCurrent(activitiesform);


            } catch (Exception c) {
                Alert alert = new Alert("Error", "The connection has failed. Please try again.", null, AlertType.ERROR);
                display.setCurrent(alert);
            }

这是我目前的Servlet

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String activityparam = request.getParameter("activity");
        String[] sports = new String[5];
        sports[0] = ("Football competition");

        if (activityparam.equals("Sports")) {
            out.println("These are the list of sporting activities \n");
            for (int i = 0; i < 5; i++) {

                out.println(sports[i]);
                //Wanted to output the images of different sports here
   }

我想要实现的是,在发送查询请求之后,Servlet可以将图像与sports [i]字符串一起显示回Midlet。现在,它只使用PrintWriter处理String文本。图像文件存储在本地,因此绝对路径应该没问题。请帮我。感谢。

1 个答案:

答案 0 :(得分:2)

我认为你应该使用两个Servlet:一个用于Strings,另一个用于图像(一次一个)。

MIDlet可以检索图像:


    Image img = Image.createImage(in);

如果您需要缓存图像数据,可以使用:


    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte buff[] = new byte[1024];
    int len = in.read(buff);

    while (len > 0) {
        baos.write(buff, 0, len);
        len = in.read(buff);
    }
    baos.close();
    buff = baos.toByteArray();
    // write to RecordStore
    Image img = Image.createImage(new ByteArrayInputStream(buff));