将编码字符串转换为java中的可读字符串

时间:2014-07-29 13:20:47

标签: java c# string unicode encoding

我正在尝试从C#程序向我的java服务器发送POST请求。 我将请求与json对象一起发送。 我在服务器上收到请求,可以使用以下java代码读取发送的内容:

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);

字符串s现在是我从C#客户端发送的json对象的表示。但是,一些角色现在搞砸了。 原json对象:

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

所以我的问题是:如何转换收到的字符串,使其看起来像原始字符串?

2 个答案:

答案 0 :(得分:2)

看起来像URL编码,所以为什么不使用java.net.URLDecoder

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

这假设Charset实际上是UTF-8

答案 1 :(得分:0)

那些看起来是URL编码的,所以我会使用URLDecoder,就像这样

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();
}

请注意,您的示例中似乎有一个额外的百分比,因为上面打印

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