开发者

Data connectivity in android: InputStream's `available` returns different values

开发者 https://www.devze.com 2023-04-05 02:36 出处:网络
The below code works in Android emulator but not in real devices. The inputstream.available() returns -1 on device while on emulator, it returns an int value in thousands. Any help?

The below code works in Android emulator but not in real devices. The inputstream.available() returns -1 on device while on emulator, it returns an int value in thousands. Any help?

code:

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


Genereally you should use the HttpClient Android provides, the Java URL Class is not robust enough.

like:

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

精彩评论

暂无评论...
验证码 换一张
取 消