android中的数据连接:InputStream的`available`返回不同的值

时间:2011-09-16 09:03:03

标签: android connection

以下代码适用于Android模拟器,但不适用于实际设备。在模拟器上,inputstream.available()在设备上返回-1,它返回数千的int值。有什么帮助吗?

代码:

try {
                URL url = new URL("http://www.google.com");
                Log.d(TAG,"Set URL");
                urlConnection = (HttpURLConnection) url.openConnection();
                //urlConnection.connect();
                Log.d(TAG,"Open connection");
                 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                Log.d(TAG,"get input");
                 str="Connect time out::"+urlConnection.getConnectTimeout()+
                     "\nContent length:"+urlConnection.getContentLength()+
                     "\nRead time out::"+ urlConnection.getReadTimeout()+
                     "\nResponse messgae::"+urlConnection.getResponseMessage()+
                     "\nAvailable bytes::::"+in.available();
                 Log.d(TAG,""+str);
                 read(in);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                urlConnection.disconnect();
            }

1 个答案:

答案 0 :(得分:2)

通常你应该使用Android提供的HttpClient,Java URL Class不够健壮。

像:

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(new URI("http://w3mentor.com/"));
    HttpResponse response = client.execute(request);
    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));