HttpUrlConnection.getInputStream 在 Android 中返回空流

2024-03-29

我使用 HttpUrlConnection 向服务器发出 GET 请求。 连接后:

  1. 我收到响应代码:200
  2. 我收到回复消息:好的
  3. 我得到输入流,没有抛出异常,但是:

    • 在一个独立的程序中,我得到了响应的正文,如预期的那样:

    {“姓名”:“我的名字”,“生日”:“01/01/1970”,“id”:“100002215110084”}

    • 在android活动中,流是空的(available()== 0),因此我无法得到 任何文本输出。

有什么提示或线索可以遵循吗?谢谢。

编辑:这是代码

请注意:我使用import java.net.HttpURLConnection;这是标准 http Java 库。我不想使用任何其他外部库。实际上 我在 android 中使用 apache 的 httpclient 库确实遇到了问题(其中一些匿名 .class 不能被 apk 编译器使用)。

好吧,代码:

URLConnection theConnection;
theConnection = new URL("www.example.com?query=value").openConnection(); 

theConnection.setRequestProperty("Accept-Charset", "UTF-8");

HttpURLConnection httpConn = (HttpURLConnection) theConnection;


int responseCode = httpConn.getResponseCode();
String responseMessage = httpConn.getResponseMessage();

InputStream is = null;
if (responseCode >= 400) {
    is = httpConn.getErrorStream();
} else {
    is = httpConn.getInputStream();
}


String resp = responseCode + "\n" + responseMessage + "\n>" + Util.streamToString(is) + "<\n";

return resp;

I see:

200
OK
响应正文

but only

200 OK

在安卓中


尝试托米斯拉夫的代码我得到了答案。

我的函数streamToString()使用.available()来感测是否收到任何数据, 在 Android 中它返回 0。当然,我打电话得太早了。

如果我宁愿使用 readLine():

class Util {
public static String streamToString(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
}

然后,它等待数据到达。

Thanks.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HttpUrlConnection.getInputStream 在 Android 中返回空流 的相关文章

随机推荐