将编码字符串转换为java中的可读字符串
本文关键字:字符串 java 编码 编码字符 转换 | 更新日期: 2023-09-27 18:15:30
我正在尝试从c#程序发送POST请求到我的java服务器。我将请求与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"}
收到的字符串:
%7b%22key1%22%3a%22value1%22%2c%22key2%22%3a%22value2%22%2c%22key3%22%3a%22value3%22%%7d
所以我的问题是:我如何转换接收的字符串,使它看起来像原来的一个?
似乎是URL编码,所以为什么不使用java.net.URLDecoder
String s = java.net.URLDecoder.decode(new String(temp), StandardCharsets.UTF_8);
这里假设字符集实际上是UTF-8
这些似乎是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"}