以下代码来自我的第一个互联网应用程序。我没有测试它,因为我没有可用的 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();
}
}
}
}