| | |
Problem with byte array to string
Thread Solved |
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
server calls follows
Any suggestions?
Servlet
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
Java Syntax (Toggle Plain Text)
before transmit name=Peter length = 23 reading data Received data = [B@1cb37664 Length 23 str = [B@1cb37664
server calls follows
Java Syntax (Toggle Plain Text)
Print income data: Peter 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
Java Syntax (Toggle Plain Text)
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class PostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); System.out.println("Print income data: " + name); String message = "Received name : '" + name + "'"; response.setContentType("text/plain"); response.setContentLength(message.length()); System.out.println("Response: " + message + " length bytes = " + message.length() ); PrintWriter out = response.getWriter(); out.println(message); } }
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
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Umm, peter, I thought you knew this one. ;-)
I believe should be
or
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). ;-)
Java Syntax (Toggle Plain Text)
str = servletData.toString();
Java Syntax (Toggle Plain Text)
str = new String(servletData);
Java Syntax (Toggle Plain Text)
str = new String(servletData, 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
----------------------------------------------
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
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
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
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
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:
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:
java Syntax (Toggle Plain Text)
public class ServletApp { public static void main(String args[]) { try { URL url = new URL("http://localhost:8080/mobile/postServlet.jsp"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); String queryString = "name=sos"; Writer out = new PrintWriter(conn.getOutputStream()); out.write(queryString); out.close(); Scanner in = new Scanner(conn.getInputStream()); System.out.println("Data received--->"); while(in.hasNext()) { System.out.print(in.next() + " "); } in.close(); } catch(Exception e) { e.printStackTrace(); } } }
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?!
Sacrifice is a painful, pure and beautiful thing.
Dammit, Jones, What the Hell Are Knoll Pointers?!
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
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
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Just side notes on some testing done
Seting up
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); has to be set or servlet will receive null from midletSeting 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
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
![]() |
Similar Threads
- Coverting a string to a byte array (Visual Basic 4 / 5 / 6)
- Storing A Long Array of bytes in an XML file. (C#)
- Problem with Generic Pointers (C)
- Noob : Input Stream Trouble (Java)
- Packets sending... (Pascal and Delphi)
- Sprintf and buffer overflow (C)
- Ports (Java)
- I've got Trojan.Holax... is this bad? (Viruses, Spyware and other Nasties)
- not-a-virusadware (Viruses, Spyware and other Nasties)
- string size problem (C)
Other Threads in the Java Forum
- Previous Thread: Need Java 1.4 MCSE solved question parers
- Next Thread: help with GUI (calling one class from other class)
Views: 8754 | Replies: 5
| Thread Tools | Search this Thread |
Tag cloud for Java
access actionlistener add android applet arguments array arrays binary bluetooth build c# chat class classes client code combobox component convert converter coordinates data database desktop draw eclipse error event exception fast file fractal game givemetehcodez graphics gui helpwithhomework html ide image inheritance input integer interface j2me java javafx jframe jmf jni jpanel jtable jtextfield lazy linked linked-list list loop method methods mobile netbeans newbie number object oracle os page parameter pattern phone pixel print printing problem program programming project read remove robot scanner search server service set size sms socket software sort sql string swing text timer translate tree web






