[英]Retrieving data from the internet
以下代碼來自我的第一個互聯網應用。 我沒有測試它,因為沒有可用的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();
}
}
}
}
您能具體一點嗎?
在我看來,您已經在檢索數據。
您的代碼應該失敗,因為您正在UI線程中做網絡工作。
當然可以,您需要遵循一些規則。
AsyncTask
下載相關作品 可以在這里找到一個工作示例: 使用JSON從api獲取信息
請參閱以上文章中的我的答案,以將數據從服務器下載到您的設備。 這個工作示例可以為您提供一個良好的開端。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.