HttpUrlConnection.getInputStream在Android中返回空流

cib*_*en1 8 android inputstream httpurlconnection

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

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

    • 在一个独立的程序中,我按预期得到了响应的主体:

    {"name":"我的名字","生日":"01/01/1970","id":"100002215110084"}

    • 在android活动中,流是空的(available()== 0),因此我无法获取任何文本.

是否有任何提示或追踪?谢谢.

编辑:这是代码

请注意:我使用import java.net.HttpURLConnection;这是标准的http Java库.我不想使用任何其他外部库.事实上,我确实在使用来自apache的库httpclient的android中遇到了问题(他们的一些匿名.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;
Run Code Online (Sandbox Code Playgroud)

我知道了:

200
OK
回复的正文

但是只有

200好的

在android中

cib*_*en1 12

尝试Tomislav的代码我得到了答案.

我的函数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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,它等待数据到达.

谢谢.