FewWords
FewWords

Reputation: 675

Convert encoded string to readable string in java

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?

Upvotes: 2

Views: 213

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201517

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"}

Upvotes: 0

gtgaxiola
gtgaxiola

Reputation: 9331

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

Upvotes: 2

Related Questions