【问题标题】:HttpUrlConnection.getInputStream returns empty stream in AndroidHttpUrlConnection.getInputStream 在 Android 中返回空流
【发布时间】:2013-02-08 09:59:00
【问题描述】:

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

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

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

    {"name":"my name","birthday":"01/01/1970","id":"100002215110084"}

    • 在 android 活动中,流为空(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
好的
响应正文

但只有

200 好的

在安卓中

【问题讨论】:

标签: android inputstream httpurlconnection


【解决方案1】:

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

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"));

【讨论】:

    【解决方案2】:

    尝试 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();
        }
    }
    

    然后,它等待数据到达。

    谢谢。

    【讨论】:

      【解决方案3】:

      您可以尝试使用此代码以字符串形式返回响应:

      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();
          }
      

      【讨论】:

        猜你喜欢
        • 2015-09-02
        • 1970-01-01
        • 1970-01-01
        • 2015-11-16
        • 2021-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多