Read contents of a URL in Android
I'm new to android and I'm trying to figure out how to get the contents of a URL as a String. For example if my URL is http://www.google.com/ I want to get the HTML for the page as a String. Could anyone help me with this?
Solution 1:
From the Java Docs : readingURL
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Instead of writing each line to System.out
just append it to a string.
Solution 2:
You can open a stream and read and append each line to a string - remember to wrap everything with a try-catch block - hope it helps!
String fullString = "";
URL url = new URL("http://example.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
Solution 3:
You can put it in an AsyncTask like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
try {
new Main2Activity.MyTask().execute(this);
} catch (Exception e) {
e.printStackTrace();
}
}
private static class MyTask extends AsyncTask<Object, Void, String> {
Main2Activity activity;
@Override
protected String doInBackground(Object... params) {
activity = (Main2Activity)params[0];
try {
StringBuilder sb = new StringBuilder();
URL url = new URL("http://www.google.com/");
BufferedReader in;
in = new BufferedReader(
new InputStreamReader(
url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
in.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String str) {
//Do something with result string
WebView webView = activity.findViewById(R.id.web_view);
webView.loadData(str, "text/html; charset=UTF-8", null);
}
}