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?

2
  • possible duplicate of How do you unescape URLs in Java? Commented Jul 29, 2014 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. Commented Jul 29, 2014 at 13:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.