how can i get the content of the URLbelow using HttpURLConnection
and put it in a TextView
?
Asked
Active
Viewed 1.3k times
3

Lii
- 11,553
- 8
- 64
- 88

mahdi azarm
- 340
- 2
- 7
- 18
-
http://stackoverflow.com/a/8655039/5202007 – Mohammad Tauqir Oct 06 '15 at 08:12
-
Possible duplicate of [Http Get using Android HttpURLConnection](http://stackoverflow.com/questions/8654876/http-get-using-android-httpurlconnection) – Mel Oct 06 '15 at 08: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 view – mahdi azarm Oct 06 '15 at 08:20
1 Answers
14
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();

Deepak Goyal
- 4,747
- 2
- 21
- 46
-
-
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. – Deepak Goyal Oct 06 '15 at 08:54
-
-
@Jamil Check the documentation. https://developer.android.com/reference/java/net/HttpURLConnection.html – Deepak Goyal Oct 10 '16 at 04:25
-
@DeepakGoyal : Yep already seen it. http://stackoverflow.com/questions/29150184/httpentity-is-deprecated-on-android-now-whats-the-alternative – Jamil Oct 10 '16 at 10:11
-
@Jamil Its `org.apache.http.client.HttpClient` which was depreceated but `HttpURLConnection` is the overcome of that. – Deepak Goyal Oct 10 '16 at 13:01