JavaIO流返回不同的位
当点击上面的RESTAPI时,这就是get打印的内容JavaIO流返回不同的位,java,arrays,stream,byte,inputstream,Java,Arrays,Stream,Byte,Inputstream,当点击上面的RESTAPI时,这就是get打印的内容 @GET @Path("/hello-message") @Produces(APPLICATION_JSON) public Response getMessage() throws Exception { char[] array = {'h','e','l','l','o', 2000, 3000, 9999}; CharArrayReader charArrayReader = new CharAr
@GET
@Path("/hello-message")
@Produces(APPLICATION_JSON)
public Response getMessage() throws Exception {
char[] array = {'h','e','l','l','o', 2000, 3000, 9999};
CharArrayReader charArrayReader = new CharArrayReader(array);
int c = 0;
while ((c = charArrayReader.read()) != -1) {
System.out.println(c + " " + Integer.toBinaryString(c) + " " +(char)c);
}
return Response.status(200).entity(charArrayReader).build();
}
显然,我使用的是Unicode(数组中的最后3个字符),因此,这些是物理位(仅上面的位部分),我认为将通过底层网络传输
但是,当我收到响应时,我从ApacheHTTPAPI以InputStream的形式获得它
104 1101000 h
101 1100101 e
108 1101100 l
108 1101100 l
111 1101111 o
2000 ߐ 11111010000
3000 101110111000 ஸ
9999 10011100001111 ✏
当我迭代InputStream中的字节时,这就是我收到的
class Test {
public static void main(String[] args) throws Exception {
HttpGet httpGet = new HttpGet("http://localhost:80/hello-message");
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpGet);
InputStream inputStream = response.getEntity().getContent();
int c = -1;
while ((c = inputStream.read()) != -1) {
System.out.println(c + " " + Integer.toBinaryString(c));
}
}
}
104 1101000
101 1100101
108 1101100
108 1101100
111 1101111
223 11011111
144 10010000
224 11100000
174 10101110
184 10111000
226 11100010
156 10011100
143 10001111
In API method it printed = 11111010000,
In Response it printed = 11011111 (223) followed by 10010000 (144) which clearly doesn't matches above. I expected 11111010000 will be broken into 2 bytes like 00000111 (7) 11010000 (208), but I received something else like, 223 and 114.
这将打印与API方法返回的字符数组相同的字符串
String s = IOUtils.toString(response.getEntity().getContent(), UTF_8);
System.out.println(s);
这种行为有什么原因吗?stream是如何将这些片段放回原处并形成正确的消息的?Eww!我真的打了一个很长的问题,我花了一天的时间才找到答案
这段9分钟的视频很精彩:自我回答很好。只有链接的答案不是:请在答案中包含相关细节,否则它不是有效答案;dr is:您首先查看unicode字符,然后查看编码的ByTestStream。区别在于用于传输它的“编码”。在您的例子中,它是UTF-8(您的代码中甚至提到了UTF-8)。
helloߐஸ✏