Read contents of a URL in Android
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.
Android - How can I read a text file from a url?
Try using an HTTPUrlConnection or a OKHTTP Request to get the info, here try this:
Always do any kind of networking in a background thread else android will throw a NetworkOnMainThread Exception
new Thread(new Runnable(){
public void run(){
ArrayList<String> urls=new ArrayList<String>(); //to read each line
//TextView t; //to show the result, please declare and find it inside onCreate()
try {
// Create a URL for the desired page
URL url = new URL("http://somevaliddomain.com/somevalidfile"); //My text file location
//First open the connection
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000); // timing out in a minute
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (Exception e) {
Log.d("MyTag",e.toString());
}
//since we are in background thread, to post results we have to go back to ui thread. do the following for that
Activity.this.runOnUiThread(new Runnable(){
public void run(){
t.setText(urls.get(0)); // My TextFile has 3 lines
}
});
}
}).start();
how to get data from url in android studio
Your code is fine. It reads HTML from a URL
This site requires Javascript to work
HttpUrlConnection does not use or render dynamic Javascript created web pages, only static html content
Try a different endpoint for JSON data...
Also, please look into using a proper HTTP library for Android rather than using AsyncTask like Okhttp or Volley
how to read and use the content of a website in android app
This part of code can help you:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new HttpTask().execute("http://www.google.com");
}
public String getWebPage(String adresse) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet();
InputStream inputStream = null;
String response = null;
try {
URI uri = new URI(adresse);
httpGet.setURI(uri);
HttpResponse httpResponse = httpClient.execute(httpGet);
int statutCode = httpResponse.getStatusLine().getStatusCode();
int length = (int) httpResponse.getEntity().getContentLength();
Log.v(LOG_THREAD_ACTIVITY, "HTTP GET: " + adresse);
Log.v(LOG_THREAD_ACTIVITY, "HTTP StatutCode: " + statutCode);
Log.v(LOG_THREAD_ACTIVITY, "HTTP Lenght: " + length + " bytes");
inputStream = httpResponse.getEntity().getContent();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
int inChar;
StringBuffer stringBuffer = new StringBuffer();
while ((inChar = reader.read()) != -1) {
stringBuffer.append((char) inChar);
}
response = stringBuffer.toString();
} catch (ClientProtocolException e) {
Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() ClientProtocolException error", e);
} catch (IOException e) {
Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() IOException error", e);
} catch (URISyntaxException e) {
Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() URISyntaxException error", e);
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException e) {
Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() IOException error lors de la fermeture des flux", e);
}
}
return response;
}
private class HttpTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
String response = getWebPage(urls[0]);
return response;
}
@Override
protected void onPostExecute(String response) {
Log.i(LOG_THREAD_ACTIVITY, "HTTP RESPONSE" + response);
textViewConsole.setText(response);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
Related Topics
@Android Display /Res/Viewable in Webview
How to Make Zoomable Linearlayout
Android - Margins Specified in Custom Style Not Taking Effect
Android SQLite Selection Args[] with Int Values
Achartengine - Can't Figure How to Use Dates as X Axis - the File I Save Is Empty
How to Prevent a Scrollview from Scrolling to a Webview After Data Is Loaded
Android Studio: How to Generate Signed APK Using Gradle
How to Work with Android's In-App Update API
Download and Extract Zip File in Android
Cannot Call Getsupportfragmentmanager() from Activity
Room - Livedata Observer Does Not Trigger When Database Is Updated
Ndk: How Include *.So Files in Androidstudio
Implement Double Click for Button in Android
Android Detect Usb Storage for Kitkat (4.4)