我使用 HttpUrlConnection 向服务器发出 GET 请求。 连接后:
- 我得到响应代码:200
- 我收到回复消息:OK
我得到了输入流,没有抛出异常但是:
- 在一个独立的程序中,我得到了响应的正文,正如预期的那样:
{"name":"我的名字","生日":"01/01/1970","id":"100002215110084"}
- 在 android Activity 中,流是空的 (available() == 0),因此我无法获取 任何文本输出。
有什么提示或线索可以遵循吗?谢谢。
编辑:这是代码
请注意:我使用 import java.net.HttpURLConnection;
这是标准的
http Java 库。 我不想使用任何其他外部库。实际上
我在 android 中使用来自 apache 的库 httpclient 确实遇到了问题(apk 编译器无法使用它们的一些匿名 .class)。
好了,代码:
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;
我明白了:
200
OK
the body of the response
只是
200 OK
在安卓中
最佳答案
尝试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();
}
}
然后,它等待数据到达。
谢谢。
关于android - HttpUrlConnection.getInputStream 在 Android 中返回空流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030026/