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()));
精彩评论