2012-09-13 118 views
0

以下代码来自我的第一个互联网应用程序。我没有测试过,因为没有WLAN可用。接下来我想要从网站上检索数据。从互联网上检索数据

是否有任何程序可以实现这样的任务?

Java代码:

public class Internet00 extends Activity { 

TextView tv00; 
public boolean isNetworkAvailable() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netWorkinfo = cm.getActiveNetworkInfo(); 

    if (netWorkinfo != null && netWorkinfo.isConnected()) { 
     return true; 
    } 
    return false; 
} 
private void readStream(InputStream in) { 
    BufferedReader reader = null; 
    try { 
     reader = new BufferedReader(new InputStreamReader (in)); 
     String line=""; 
     while ((line=reader.readLine()) != null) 
      tv00.setText(line); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (reader != null) { 
      try { 
      reader.close(); 
      } catch (IOException e) { 
      e.printStackTrace(); 
      } 
     } 
    } 
} 
@SuppressLint({ "ParserError", "NewApi" }) 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_internet00); 

    tv00 = (TextView) findViewById(R.id.tv00); 
    if(isNetworkAvailable()) { 
     StrictMode.ThreadPolicy policy = new StrictMode. 
      ThreadPolicy.Builder().permitAll().build(); 
      StrictMode.setThreadPolicy(policy); 

    try { 
      URL url = new URL("http://www.vogella.com"); 
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); 
      readStream(con.getInputStream()); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      } 
     } 
    } 
} 

回答

0

你能成为一个更具体一点?

它在我看来像你正在检索数据。

你的代码应该失败,因为你正在UI线程中做网络的东西。

+0

我的意思是如果网站包含表格的数据,如何检索这些数据按行或根据列名 – LetsamrIt

+0

你必须解析的HTML。有几个选项可以解析html。我的建议是[jsoup library](http://jsoup.org/)。它的快速和易于使用。 – andre

0

是的,当然,你需要遵循一些规则。

  1. ,请不要使用网线在UI线程
  2. 使用AsyncTask下载相关的工作

工作示例可以在这里找到:Getting info from api using JSON

请参阅我的答案在上述职位将数据从服务器下载到您的设备。这个工作例子对你来说可能是一个好的开始。