2013-01-21 22 views
0

這是代碼,它必須加載頁面並將其存儲在string[]中。我不明白這個問題,因爲它不是加載頁面,它是沒有錯誤無法使用http請求獲取頁面

如果有任何人知道任何更好的方式發送http請求然後請張貼它或請告訴我這個問題。

//some code  
    btnShowLocation.setOnClickListener(new View.OnClickListener() { 
       int j=0; 
       @Override 
       public void onClick(View v) { 
        // TODO Auto-generated method stub 

        new MyTask().execute();});  
    //some code 

    private class MyTask extends AsyncTask<Void, Void, Void> { 
        @Override 
        protected Void doInBackground(Void... params) { 
         // TODO Auto-generated method stub 

         try { 

          String ssr=""; 
          URL n = new URL("http://maps.google.co.in/maps?hl=en&q=nagpur+to+pune"); 
          URLConnection nc = null; 
          nc = n.openConnection(); 
          BufferedReader in = null; 
          in = new BufferedReader(new InputStreamReader(nc.getInputStream())); 
          String inputLine; 
          while ((inputLine = in.readLine()) != null) { 
           ssr+=inputLine; 
          } 

          Document doc = Jsoup.parse(ssr); 
          Elements el = doc.getElementsByClass("dir-mrgnr"); 
          String str = el.text(); 
          str = str.replaceAll("[0-9]+[.] ", "\n"); 
          string = str.split("\n"); 
         } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 

         return null; 
        } 

        @Override 
        protected void onProgressUpdate(Void... values) { 
         // TODO Auto-generated method stub 
         super.onProgressUpdate(values); 
         Toast.makeText(
           getApplicationContext(), 
           "in Background", 
           Toast.LENGTH_LONG).show(); 
         speakOut("not Working"); 
         //speakOut("work in progress"); 
        } 

        @Override 
        protected void onPostExecute(Void result) { 
         // TODO Auto-generated method stub 

         super.onPostExecute(result); 

        } 

       } 
+0

我猜這只是一個錯字,但是'yahoo.openConnection()'是什麼?它應該是'n.openConnection()'。 –

+0

不,這不是問題...新代碼不工作..... – nsp

回答

2

你不需要下載頁面並解析它。

List<String> list = new ArrayList<>(); // Better than an array 

Document doc = Jsoup.connect("http://maps.google.co.in/maps?hl=en&q=nagpur+to+pune").get(); // Connect to url and parse its conntent 
Elements el = doc.select("*.dir-mrgnr"); // Every tag with 'dir-mrgnr' class - or use getElementsByClass() as you did 

for(Element element : el) 
{ 
    list.add(element.text()); 
} 

Btw。使用+= on a String in a loop;使用一個StringBuilder instdead!