how can i get the content of the URLbelow using HttpURLConnection and put it in a TextView?
3
-
stackoverflow.com/a/8655039/5202007Mohammad Tauqir– Mohammad Tauqir2015-10-06 08:12:03 +00:00Commented Oct 6, 2015 at 8:12
-
Possible duplicate of Http Get using Android HttpURLConnectionMel– Mel2015-10-06 08:20:16 +00:00Commented Oct 6, 2015 at 8:20
-
thanks i seen this before asking but it doesn't help me the content in the url is "TUTORIAL 20 WORKED, WE GOT CONNECTION" and i want to get this text from url then put it in a text viewmahdi azarm– mahdi azarm2015-10-06 08:20:36 +00:00Commented Oct 6, 2015 at 8:20
Add a comment
|
1 Answer
class GetData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
String result = "";
try {
URL url = new URL("http://ephemeraltech.com/demo/android_tutorial20.php");
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
}
in.close();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result;
}
@Override
protected void onPostExecute(String result) {
yourTextView.setText(result);
super.onPostExecute(s);
}
}
and call this class by using
new GetData().execute();
6 Comments
mahdi azarm
thanks man it's worked but can i do that without create a class?
Deepak Goyal
it is network operation and must be perform on separate thread. So you need the asyncTask class. Because asynctask is the best option to perform network operations.
Jam
Depreciated now
Deepak Goyal
@Jamil Check the documentation. developer.android.com/reference/java/net/HttpURLConnection.html
Jam
@DeepakGoyal : Yep already seen it. stackoverflow.com/questions/29150184/…
|