2

I am trying to send a POST request from a C# program to my java server. I send the request together with an json object. I recive the request on the server and can read what is sent using the following java code:

BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
OutputStream out = conn.getOutputStream();
String line = reader.readLine();
String contentLengthString = "Content-Length: ";
int contentLength = 0;
while(line.length() > 0){   
    if(line.startsWith(contentLengthString))
        contentLength = Integer.parseInt(line.substring(contentLengthString.length()));             
    line = reader.readLine();
}       
char[] temp = new char[contentLength];
reader.read(temp);  
String s = new String(temp);

The string s is now the representation of the json object that i sent from the C# client. However, some characters are now messed up. Original json object:

{"key1":"value1","key2":"value2","key3":"value3"}

recived string:

%7b%22key1%22%3a%22value1%22%2c%22key2%22%3a%22value2%22%2c%22key3%22%3a%22value3%22%%7d

So my question is: How do I convert the recived string so it looks like the original one?

FewWords
  • 595
  • 1
  • 5
  • 22
  • possible duplicate of [How do you unescape URLs in Java?](http://stackoverflow.com/questions/623861/how-do-you-unescape-urls-in-java) – radai Jul 29 '14 at 13:26
  • That duplicate is a bad one. The author of the accepted answer never bothered to update their answer (which uses a deprecated method call). The answers below here are better. – Erwin Bolwidt Jul 29 '14 at 13:56

2 Answers2

2

Seems like URL Encoded so why not use java.net.URLDecoder

String s = java.net.URLDecoder.decode(new String(temp), StandardCharsets.UTF_8);

This is assuming the Charset is in fact UTF-8

gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
0

Those appear the be URL encoded, so I'd use URLDecoder, like so

String in = "%7b%22key1%22%3a%22value1%22%2c%22key2"
    + "%22%3a%22value2%22%2c%22key3%22%3a%22value3%22%7d";
try {
  String out = URLDecoder.decode(in, "UTF-8");
  System.out.println(out);
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
}

Note you seemed to have an extra percent in your example, because the above prints

{"key1":"value1","key2":"value2","key3":"value3"}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249