Android:访问网站的URL连接

时间:2017-10-02 09:01:14

标签: android random urlconnection

我使用以下代码从网站中提取详细信息。

代码:

private class FetchAllData extends AsyncTask<Void, Void, Void> 
    {
         @Override
         protected void onPreExecute() 
         {
             super.onPreExecute();              
             Utilities.custom_toast(CurrentResult.this, "Refreshing", "gone!", "short", "vertical");
         }

         @Override
         protected Void doInBackground(Void... params) 
         {
            try 
            {
                //String urlX = URL1 + "?x=" + new Random().nextInt(100000); //Method1
                String urlX = URL1 //Method2;
                URL url = new URL(""+ urlX);
                URLConnection con = url.openConnection();
                con.setUseCaches(false); //This will stop caching!
                // BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                PageCode = "";
                OriginalPageCode = "";
                while ((inputLine = in.readLine()) != null) 
                {
                    PageCode += inputLine;
                }                   
                OriginalPageCode = PageCode;
                toast_IshtmlObtained = urlX+ "\nHTML success obtained as follows:\n\n";
                try
                {
                    extract_website_and_save();
                    toast_IsInfoExtracted = "success extracting website";
                }
                catch (Exception e1)
                {
                    toast_IsInfoExtracted = "error extracting website";
                }

                in.close();
            } 
            catch (Exception e) 
            {
                PageCode = "ERROR: " + e;
                toast_IshtmlObtained = "HTML not obtained:\nHTML retrieved as follows:" + PageCode;
            }
            return null;
         }

         @Override
         protected void onPostExecute(Void result) 
         { 
             Utilities.custom_toast(CurrentResult.this, "Done", "gone!", "short", "vertical");

             setText();
             ......
         }
     }

问题:

事先我在Method1中使用了URL,并成功访问并提取了网站详细信息。但是,在这些日子里它不起作用。我现在尝试了Method2,现在可以使用了。

我想问一下

  1. 如果访问网站的用户数量巨大,则Method1中的随机数对于防止缓存很重要,

  2. 如果在Method2中使用直接网址有什么缺点?感谢。

  3. 在URLConnection con.addHeader("Cache-Control", "no-cache");下添加会解决问题吗?

1 个答案:

答案 0 :(得分:0)

尝试使用retrofit2.0或快速安卓网络库连接外部网络Apis。它比使用AsycTask更易读,更易读 这里有一些有用的链接,可以教你如何使用它们

https://github.com/amitshekhariitbhu/Fast-Android-Networking它为所有外部连接提供了惊人的库

此外,使用标准lib进行解析,如gson

http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html