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   }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM