Reading UTF8 strings from a server through http using MIDP
Asked Answered
D

1

5

I want to read UTF-8 strings from a server that I have control of, using java MIDP. My server is sending UTF-8 data. The following code gets close:

        c = (StreamConnection) Connector.open(
             myServer, Connector.READ_WRITE);
        InputStream is = c.openInputStream();
        StringBuffer sb = new StringBuffer();
        int ch;
        while((ch = is.read()) != -1)
            sb.append((char)ch + "->" + ch + "\n");

I print the char and its code to debugging purposes. I think it is reading ASCII chars here, so, when I have some char that has its code above 127 then I get two chars, like the two examples bellow:

letter á. UTF code E1 (hex). I get 195 and then 161

letter ô. UTF code F4 (hex). I get 195 and then 180

My question is, is there a way for me to read UTF characters directly. I've found some solutions in the web but none fits to the MIDP.

Demello answered 8/7, 2009 at 2:45 Comment(0)
H
10

Instead of reading bytes, read characters. Use an InputStreamReader API to convert bytes to characters and run through the UTF-8 encoder. It should be supported as part of the JavaME CLDC (JSR 30) profile; that's where the link points.

Try something like this:

c = (StreamConnection) Connector.open(
         myServer, Connector.READ_WRITE);
Reader r = new InputStreamReader(c.openInputStream(), "UTF-8");
StringBuffer sb = new StringBuffer();
int ch;
while((ch = r.read()) != -1)
    sb.append((char)ch + "->" + ch + "\n");
Hookup answered 8/7, 2009 at 3:55 Comment(1)
Thanks for the great answer it helped meg a lot. One little comment, on this row: Reader r = InputStreamReader(c.openInputStream(), "UTF-8");, It only work for me if I use it this way: Reader r = new InputStreamReader(c.openInputStream(), "UTF-8"); Again thanks!!!!Hopehopeful

© 2022 - 2024 — McMap. All rights reserved.