0

I have a Java servlet which takes some data from an android app and returns a string data back to the android app using the following code.

response.getOutputStream().write(STRING_MESSAGE.getBytes());

The value I pass here is read from the android activity as:

InputStream is = con.getInputStream();
byte[] b = new byte[1024];
while(is.read(b) != -1) {
    buffer.append(new String(b));
}

The value is then converted to String using:

String result = buffer.toString();

But after doing so, the result has some added unwanted characters (they appear as a '?' inside a diamond shape) appended to the original string I have passed from the servlet. How can I avoid this?

shyam
  • 1,348
  • 4
  • 19
  • 37
  • I'm guessing they are utf-8 values. just make sure you handle them correctly when you print them out. ofcourse based on your output stream sometimes you can't deal with them. for example in command prompt special chars will be some funny shapes. – nafas Jul 04 '14 at 09:48
  • @nafas I'm actually printing it out to logcat to see the result. But even when I compare it to the exact same string, they don't match. – shyam Jul 04 '14 at 10:06
  • this link will hopefully help u.[utf-8](http://stackoverflow.com/questions/14918188/reading-text-file-with-utf-8-encoding-using-java) – nafas Jul 04 '14 at 10:09
  • @nafas I've tried both UTF-8 and windows-1256 now. Still couldn't fix it! – shyam Jul 04 '14 at 10:30

1 Answers1

0

As nafas said, the encoding is probably the error. Try to replace the writing on your os with this :

response.getOutputStream().write(STRING_MESSAGE.getBytes(Charset.forName("UTF-8")));

And you also have to apply the mod to the InputStream :

buffer.append(new String(b, Charset.forName("UTF-8")));
  • What charset are you using on your servlet and on your android vm ? – Zantoinef Jul 04 '14 at 10:54
  • I've tried using both UTF-8 and windows-1256 in both the servlet code as well as the android code. – shyam Jul 04 '14 at 11:14
  • That's really weird... Maybe try to use some Reader and Writer instead of basic stream to avoid encoding problem (I don't see how it can't be encoding problem.) – Zantoinef Jul 04 '14 at 16:56
  • It sure is weird! I've used the same code elsewhere a number of times and never had a problem. But when I tried passing a fixed length String and then reading it using a byte[] of same length, I get the right result even without using any of the Charset stuff. – shyam Jul 05 '14 at 04:51