HttpUrlConnection.getInputStream返回的Android空流(HttpU

2019-08-17 03:00发布

I make a GET request to a server using HttpUrlConnection. After connecting:

  1. I get response code: 200
  2. I get response message: OK
  3. I get input stream, no exception thrown but:

    • in a standalone program I get the body of the response, as expected:

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

    • in a android activity, the stream is empty (available() == 0), and thus I can't get any text out.

Any hint or trail to follow? Thanks.

EDIT: here it is the code

Please note: I use import java.net.HttpURLConnection; This is the standard http Java library. I don't want to use any other external library. In fact I did have problems in android using the library httpclient from apache (some of their anonymous .class can't be used by the apk compiler).

Well, the code:

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;

I see:

200
OK
the body of the response

but only

200 OK

in android

Answer 1:

试图托米斯拉夫的我已经得到了答案的代码。

我的功能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();
    }
}

然后,它等待数据的到来。

谢谢。



Answer 2:

您可以使用此代码,将在返回字符串响应尝试:

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


Answer 3:

流数据可能还没有准备好,所以你应该在一个循环的流中的数据是试图访问它之前可查。 一旦数据准备好了,你应该读它,并像一个字节数组另一个地方存放; 二进制流对象是一个很好的选择,以读取数据作为一个字节数组。 其原因在于一个字节数组是一个更好的选择是因为数据可能会像的图像文件等的二进制数据

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


文章来源: HttpUrlConnection.getInputStream returns empty stream in Android