Problem with byte array to string

Thread Solved

Join Date: Dec 2004
Posts: 4,515
Reputation: peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of 
Solved Threads: 520
Moderator
Featured Poster
peter_budo's Avatar
peter_budo peter_budo is offline Offline
Code tags enforcer

Problem with byte array to string

 
0
  #1
Dec 19th, 2007
Ahh, long time since I was on pposting end

Ok here it goes. The code bellow show mobile application that takes string from user and past it on to servlet. Servlet read it add extra data on front of message and send it back to mobile device that display this new message.

My problem is the red marked part. I'm able to read correct length of sent bytes from server, I'm able to store it in byte array but can not convert back to string.

application system calls will be like this
  1. before transmit name=Peter
  2. length = 23
  3. reading data
  4. Received data = [B@1cb37664
  5. Length 23
  6. str = [B@1cb37664

server calls follows
  1. Print income data: Peter
  2. Response: Received name : 'Peter' length bytes = 23

Any suggestions?

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class GetNpost extends MIDlet implements CommandListener, Runnable
{
    private Display display;
    private Form fmMain;
    private Alert alError;
    private Command cmPOST;
    private Command cmEXIT;
    private TextField tfName;
    private StringItem response;
    private String errorMsg = null;
    //private Thread t;
    private String name;

    private void initialize()
    {
        display = Display.getDisplay(this);

        cmPOST = new Command("POST", Command.SCREEN, 2);
        cmEXIT = new Command("EXIT", Command.EXIT, 1);

        tfName = new TextField("Name:", "", 10, TextField.ANY);

        response = new StringItem("Response: ", "");

        fmMain = new Form("Post Connection");

        fmMain.append(tfName);
        fmMain.append(response);

        fmMain.addCommand(cmEXIT);
        fmMain.addCommand(cmPOST);

        fmMain.setCommandListener(this);
    }

    public void startApp()
    {
        initialize();
        //display = Display.getDisplay(this);
        display.setCurrent(fmMain);
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional){}

    public void commandAction(Command c, Displayable s)
    {
        if(c == cmPOST)
        {
            name = tfName.getString();

            try
            {
                Thread t = new Thread(this);
                t.start();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        else if(c == cmEXIT)
        {
            destroyApp(false);
            notifyDestroyed();
        }
    }

    public void run()
    {
        HttpConnection http = null;
        OutputStream oStrm = null;
        DataInputStream iStrm = null;
        boolean ret = false;

        String url = "http://localhost:8080/mobile/postServlet.jsp";  // local Tomcat        

        try
        {
            http = (HttpConnection)Connector.open(url);

            http.setRequestMethod(HttpConnection.POST);

            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            byte data[] = ("name=" + tfName.getString()).getBytes();
            System.out.println("before transmit " + new String(data));
            oStrm = http.openOutputStream();
            oStrm.write(data);
            oStrm.close();
            oStrm = null;

            iStrm = http.openDataInputStream();
            ret = processServerResponce(http, iStrm);
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
        finally
        {
            try{
            if(iStrm != null) iStrm.close();
            if(oStrm != null) oStrm.close();
            if(http != null) http.close();
            }
            catch(IOException ioe){}
        }
        if(ret == false)
        {
            showAlert(errorMsg);
        }
    }

    private boolean processServerResponce(HttpConnection http, DataInputStream dStrm) throws IOException
    {
        errorMsg = null;

        if(http.getResponseCode() == HttpConnection.HTTP_OK)
        {
            int length = (int) http.getLength();
            System.out.println("length = " + length);
            String str;
            if(length != -1)
            {
                System.out.println("reading data");
                byte servletData[] = new byte[length];
                //iStrm.read(servletData);
                //DataInputStream dis = http.openDataInputStream();
                dStrm.readFully(servletData);
                System.out.println("Received data = " + servletData + "\nLength " + servletData.length);
                str = servletData.toString();
                System.out.println("str = " + str);
            }
            else
            {
                ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

                int ch;
                while((ch = dStrm.read()) != -1)
                {
                    bStrm.write(ch);
                }
                str = new String(bStrm.toByteArray());
                bStrm.close();
            }

            response.setText(str);
            return true;
        }
        else
        {
            errorMsg = new String(http.getResponseMessage());
            return false;
        }

    }

    private void showAlert(String msg)
    {
        System.out.println(msg);
        alError = new Alert("Error", msg, null, AlertType.ERROR);

        alError.setTimeout(Alert.FOREVER);

        display.setCurrent(alError, fmMain);
    }
}

Servlet
  1. import javax.servlet.http.*;
  2. import javax.servlet.*;
  3. import java.io.*;
  4.  
  5. public class PostServlet extends HttpServlet
  6. {
  7. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  8. {
  9. String name = request.getParameter("name");
  10. System.out.println("Print income data: " + name);
  11. String message = "Received name : '" + name + "'";
  12. response.setContentType("text/plain");
  13. response.setContentLength(message.length());
  14. System.out.println("Response: " + message + " length bytes = " + message.length() );
  15. PrintWriter out = response.getWriter();
  16. out.println(message);
  17. }
  18. }
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)

LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Reply With Quote Quick reply to this message  
Join Date: Feb 2006
Posts: 2,609
Reputation: masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of masijade has much to be proud of 
Solved Threads: 282
Moderator
masijade's Avatar
masijade masijade is offline Offline
Posting Maven

Re: Problem with byte array to string

 
1
  #2
Dec 20th, 2007
Umm, peter, I thought you knew this one. ;-)

  1. str = servletData.toString();
I believe should be
  1. str = new String(servletData);
or
  1. str = new String(servletData, charset);
if the "bytes" are neither ascii, nor UTF, nor the local charset.

The second one (with the toByteArray()) is correct, but if its not working then check out the charset variation.

And Merry Christmas and a Happy New Year! (and if you're not Catholic/Christian/Other Derivatives don't take offense). ;-)
Last edited by masijade; Dec 20th, 2007 at 1:33 am. Reason: happy info
Java Programmer and Sun Systems Administrator

----------------------------------------------

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan
Reply With Quote Quick reply to this message  
Join Date: Dec 2004
Posts: 4,515
Reputation: peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of 
Solved Threads: 520
Moderator
Featured Poster
peter_budo's Avatar
peter_budo peter_budo is offline Offline
Code tags enforcer

Re: Problem with byte array to string

 
0
  #3
Dec 20th, 2007
Hehe, I can't know everything, still in process of learning also I did not have lot of byte array processing till now when I started mobile computing.
Thanx for help, charset encoding was the key
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)

LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 7,767
Reputation: ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of 
Solved Threads: 493
Super Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Failure as a human

Re: Problem with byte array to string

 
0
  #4
Dec 21st, 2007
If all you want to send is character data, why convert it to a byte stream unless what you posted was just a dummy example.

Some things you should know:
  • application/x-www-form-urlencoded is the default content type used to encode the form data, you don't need to explicitly set it. Similarly, the default content type of an HTTP servlet is text/html.
  • application/x-www-form-urlencoded is the wrong content type if you are sending bytes, you should use multipart/form-data to indicate that your request body contains binary data. (The term request body is relevant only when you are 'POST'ing your data)
  • For sending character only data you should consider constructing a query string having your data in the name-value format and posting it. Here is a small example:

  1. public class ServletApp {
  2. public static void main(String args[]) {
  3. try {
  4. URL url = new URL("http://localhost:8080/mobile/postServlet.jsp");
  5. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  6. conn.setDoOutput(true);
  7. conn.setDoInput(true);
  8. conn.setRequestMethod("POST");
  9. String queryString = "name=sos";
  10. Writer out = new PrintWriter(conn.getOutputStream());
  11. out.write(queryString);
  12. out.close();
  13. Scanner in = new Scanner(conn.getInputStream());
  14. System.out.println("Data received--->");
  15. while(in.hasNext()) {
  16. System.out.print(in.next() + " ");
  17. }
  18. in.close();
  19. }
  20. catch(Exception e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }
I don't accept change; I don't deserve to live.

Sacrifice is a painful, pure and beautiful thing.

Dammit, Jones, What the Hell Are Knoll Pointers?!
Reply With Quote Quick reply to this message  
Join Date: Dec 2004
Posts: 4,515
Reputation: peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of 
Solved Threads: 520
Moderator
Featured Poster
peter_budo's Avatar
peter_budo peter_budo is offline Offline
Code tags enforcer

Re: Problem with byte array to string

 
0
  #5
Dec 21st, 2007
The problem is I'm little limited on methods available to J2ME, the large code is example from IBM that is widely used with some of my additions for quick learning purpose befor I dive into my coursework.
But I will look more on content type also dig around litle for use of base64 and bouncing castle
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)

LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Reply With Quote Quick reply to this message  
Join Date: Dec 2004
Posts: 4,515
Reputation: peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of 
Solved Threads: 520
Moderator
Featured Poster
peter_budo's Avatar
peter_budo peter_budo is offline Offline
Code tags enforcer

Re: Problem with byte array to string

 
0
  #6
Dec 21st, 2007
Just side notes on some testing done
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); has to be set or servlet will receive null from midlet
Seting up multipart/form-data on servlet side resolve problem with providing charset on midlet side to read byte array. This may be trivial to somebody but all new things to me
Last edited by peter_budo; Dec 21st, 2007 at 7:35 am.
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)

LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 8754 | Replies: 5
Thread Tools Search this Thread



Tag cloud for Java
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2010 DaniWeb® LLC