当我收到较小长度的HTTP请求时,它很好,但是当收到长数据包被破坏时。我通过线鲨进行了追踪,并在JAVA控制台中打印了十六进制值的数据包。该打印中显示了一些其他值。为什么? 我该如何解决?
将HTTP请求转换为Hex是否有任何问题。
以下代码用于将String转换为Hex。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream responseData = request.getInputStream();
byte[] buffer = new byte[1000];
int bytesRead = 0;
while ((bytesRead = responseData.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
sb=baos.toString();
str = baos.toString();
sb.append(str);
sb = new String(baos.toByteArray(),UTF8);
}
baos.close(); // connection.close();
答案 0 :(得分:0)
在读取所有输入之前,您无法将读取的字节转换为String
,因为输入的一小部分可能是无效的UTF-8编码数据。
也不要使用ByteArrayOutputStream.toString()
,因为它使用平台的默认字符集将字节解码为字符(String
),这是不确定的。而是使用ByteArrayOutputStream.toString(String charsetName)
并指定编码。
此外,您应该使用ServletRequest.getCharacterEncoding()
检测编码并恢复为UTF-8
,例如,如果未知。
首先阅读所有输入,然后将其转换为String
:
String encoding = ServletRequest.getCharacterEncoding();
if (encoding == null)
encoding = "UTF-8";
// First read all input data
while ((bytesRead = responseData.read(buffer)) > 0) {
baos.write(buffer, 0, bytesRead);
}
// We have all input, now convert it to String:
String text = baos.toString(encoding);
由于您将二进制输入转换为String
,因此您应使用ServletRequest.getReader()
而不是使用ServletRequest.getInputStream()
读取二进制数据并手动将其转换为String
。
E.g。阅读所有内容:
BufferedReader reader = request.getReader();
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// Process line, here I just append it to a StringBuilder
sb.append(line);
// If you want to preserve newline characters, keep the next line:
sb.append('\n');
}