The following code is from my first internet app. I have not tested it because there is no WLAN available for me. What I want to do next is to retrieve data from the website.
Is there any procedure to follow to achieve such task?
JAVA Code:
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();
}
}
}
}
Could you be a little more specific?
It looks to me like you're retrieving the data already.
Your code should fail, because of you're doing network stuff in the UI Thread.
Yes of-course, you need to follow some rules.
AsyncTask
for download related works A working example can be found here : Getting info from api using JSON
Refer my answer in above post to download data from a server to your device. This working example can be a good start for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.