问题描述
我使用HttpUrlConnection向服务器发出GET请求.连接后:
I make a GET request to a server using HttpUrlConnection.After connecting:
- 我收到响应代码:200
- 我收到响应消息:OK
-
我得到了输入流,没有异常,但是:
- I get response code: 200
- I get response message: OK
I get input stream, no exception thrown but:
- 在独立程序中,按预期方式获得响应的正文:
{"name":我的名字",生日":"01/01/1970","id":"100002215110084"}
{"name":"my name","birthday":"01/01/1970","id":"100002215110084"}
- 在android活动中,流为空(available()== 0),因此我无法获取任何文字.
- in a android activity, the stream is empty (available() == 0), and thus I can't getany text out.
是否有任何提示或线索?谢谢.
Any hint or trail to follow? Thanks.
这是代码
请注意:我使用的是import java.net.HttpURLConnection;
,这是标准http Java库. 我不想使用任何其他外部库.实际上我在使用apache库中的httpclient库的android中确实遇到了问题(apk编译器无法使用其某些匿名.class).
Please note: I use import java.net.HttpURLConnection;
This is the standardhttp Java library. I don't want to use any other external library. In factI did have problems in android using the library httpclient from apache (some of their anonymous .class can't be used by the apk compiler).
好吧,代码:
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;
我知道了
但仅
在Android中
推荐答案
尝试Tomislav的代码,我找到了答案.
Trying the code of Tomislav I've got the answer.
我的函数streamToString()使用.available()来检测是否接收到任何数据,并在Android中返回0.当然,我打得太早了.
My function streamToString() used .available() to sense if there is any data received,and it returns 0 in Android. Surely, I called it too soon.
如果我宁愿使用readLine():
If I rather use 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();
}
}
然后,它等待数据到达.
then, it waits for the data to arrive.
谢谢.
这篇关于HttpUrlConnection.getInputStream在Android中返回空流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!