HttpUrlConnection.getInputStream在Android中返回空流

问题描述 投票:8回答:3

我使用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;

我知道了:

200 好 回应的主体

但是只有

200好的

在android中

android inputstream httpurlconnection
3个回答
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();
    }
}

然后,它等待数据到达。

谢谢。


4
投票

您可以尝试使用此代码返回String中的响应:

public String ReadHttpResponse(String url){
        StringBuilder sb= new StringBuilder();
        HttpClient client= new DefaultHttpClient();     
        HttpGet httpget = new HttpGet(url);     
        try {
            HttpResponse response = client.execute(httpget);
            StatusLine sl = response.getStatusLine();
            int sc = sl.getStatusCode();
            if (sc==200)
            {
                HttpEntity ent = response.getEntity();
                InputStream inpst = ent.getContent();
                BufferedReader rd= new BufferedReader(new InputStreamReader(inpst));
                String line;
                while ((line=rd.readLine())!=null)
                {
                    sb.append(line);
                }
            }
            else
            {
                Log.e("log_tag","I didn't  get the response!");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

0
投票

Stream数据可能尚未就绪,因此您应该在尝试访问之前检查流中的数据是否可用。一旦数据准备就绪,你应该读取它并存储在另一个地方,如字节数组;二进制流对象是将数据作为字节数组读取的不错选择。字节数组是更好选择的原因是因为数据可能是二进制数据,如图像文件等。

InputStream is = httpConnection.getInputStream();

byte[] bytes = null;

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] temp = new byte[is.available()];
while (is.read(temp, 0, temp.length) != -1) {
    baos.write(temp);
    temp = new byte[is.available()];
}

bytes = baos.toByteArray();

在上面的代码中,bytes是作为字节数组的响应。如果它是文本数据,您可以将其转换为字符串,例如,数据为utf-8编码文本:

String text = new String(bytes, Charset.forName("utf-8"));
© www.soinside.com 2019 - 2024. All rights reserved.