问题
how can i get the content of the URLbelow using HttpURLConnection
and put it in a TextView
?
http://ephemeraltech.com/demo/android_tutorial20.php
回答1:
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();
来源:https://stackoverflow.com/questions/32964827/get-text-from-a-url-using-android-httpurlconnection