Android中使用URL从网络上获取data

从一个http server获取一些文本,大小应该是小于1KB,下载用不了0.1秒,但是使用URL的openStream()获取这个数据的inputstream要花费5~10秒,代码如下:

 1 try {
 2    System.out.println("begin get url");
 3    URL url = new URL(murl);
 4    System.out.println("get url success");
 5    is = url.openStream();
 6    System.out.println("get inputstream success");
 7   } catch (MalformedURLException e) {
 8    // TODO Auto-generated catch block
 9    e.printStackTrace();
10   } catch (IOException e) {
11    // TODO Auto-generated catch block
12    e.printStackTrace();
13   }

 解决方法:使用如下方法可以代替,整体延时不超过1秒

 1   HttpGet httpGet = new HttpGet(murl);
 2   HttpClient httpclient = new DefaultHttpClient();
 3   // Execute HTTP Get Request
 4   HttpResponse response = null;
 5   try {
 6    response = httpclient.execute(httpGet);
 7   } catch (ClientProtocolException e) {
 8    // TODO Auto-generated catch block
 9    e.printStackTrace();
10   } catch (IOException e) {
11    // TODO Auto-generated catch block
12    e.printStackTrace();
13   }
14         try {
15    InputStream is = response.getEntity().getContent();
16   } catch (IllegalStateException e) {
17    // TODO Auto-generated catch block
18    e.printStackTrace();
19   } catch (IOException e) {
20    // TODO Auto-generated catch block
21    e.printStackTrace();
22   }

 

posted @ 2012-05-17 18:15  maliqian  阅读(6403)  评论(0编辑  收藏  举报