[英]Android Java: Get Response Body from HttpUrlConnection
I have an HttpUrlConnection
and I can get response Headers
from it like below: 我有一个
HttpUrlConnection
,可以从中获取响应标Headers
,如下所示:
How to read full response from HttpURLConnection? 如何从HttpURLConnection读取完整响应?
But I've tried many ways to get the response Body
without success. 不过,我已经尝试过很多办法获得响应
Body
没有成功。 For example: 例如:
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
return sb.toString();
Or 要么
Other ways... (With UTF-8 Encoding and ...)
The problem is that the result contains invalid character. 问题是结果包含无效字符。 For instance if the response is an image, I cannot have the correct image and it contains invalid characters:
例如,如果响应是图像,则我无法获得正确的图像,并且其中包含无效字符:
The Correct Image: 正确的图像:
‰PNG
IHDR è £ ؟£?b pHYs ڑœ
OiCCPPhotoshop ICC profile xعSgTSé=÷قôBKˆ€”KoR RB‹€‘&*! Jˆ!،ظQءEEب ˆژژ€ŒQ,ٹ
The Incorrect Image: (What I've got from response body) 图片不正确 :(我从响应正文中得到的内容)
<>�t:�t�R���k�ҥ��c�ƍZ�n�6mڤW^y���
6���/y�1���B��������ƍ;
�˖-�'�|�+V��h�Z�e�3����%%%)--M�����/�� � �}h��m6�JKK��Oh�����㏽�QWW���T%&&*++��s���ph���III�<�%%%)<<�#�),,L+V����ý����TII����x�b=��*--�Z���M�2�l�nt�ө��|�{�z��ǵe���<??_�g�VVV���={��?^�|��wF����<͟?_���gmP: �:� �C�|���t�R���r:�z������{}���B���k���o�$
>\���^�?!!AkլY�$�j�%Wq�ݮu��i���r:�
How can I get the response body from HttpUrlConnection
WITHOUT any changes with correct characters (formatting, encoding and ...)? 我怎样才能得到响应主体
HttpUrlConnection
没有正确的字符(格式,编码和...)什么变化?
If the body is a PNG image, it will be binary data, and you're expected to use the inputstream, not a reader. 如果主体是PNG图像,它将是二进制数据,并且您应该使用输入流,而不是阅读器。
UPDATE: 更新:
Example: to store the image in file "myimage.png": 示例:将图像存储在文件“ myimage.png”中:
try (InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream("myimage.png")) {
byte[] buf = new byte[4096];
int n;
while ((n = in.read(buf)) > 0) {
out.write(buf, 0, n);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.