Reputation: 9373
I can't figure out how exactly to get a simple string from an url. I have tried several versions of this code:
String str = null;
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
With all the proper manifest permissions but can't get to return anything. My txt file just contains
www.google.com
and I can access it from the phone or computer in any browser. Any ideas?
Upvotes: 0
Views: 4669
Reputation: 95368
I'm not surprised that this doesn't tell you what's wrong, if I look at your code:
} catch (MalformedURLException e) {
} catch (IOException e) {
}
If an error occurs, you won't notice anything. Just place some kind of error reporting into theses catch
branches and look at your logs. By the way, mysite.com/thefile.txt
is not an URL, while http://mysite.com/thefile.txt
is.
Upvotes: 2
Reputation: 9373
I found the answer here.
Here is the code:
Use the DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://www.urlOfThePageYouWantToRead.nl/text.txt");
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
TextView.setText(total);
Upvotes: 0