Android server data fetch
I want to fetch some data from a server protected with an username and password . I know both the username and password . Since the server is live , the data is continuing changing I need to fetch data every minute to update the application's status . The only function I know that can fetch data and turn it to a string is :
private String getPage() {
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://mywebsite.me");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
Since the server has a logon screen I don't kn开发者_如何学Goow how to get pass it . So , i'd like help with 2 thigs :1. getting the data from the server and 2. every 1 or 2 minutes I need to refresh my app and fetch again the data .
You can try this for the post object. Pre-emptive authentication is done this way.
HttpPost post = new HttpPost(url);
// Prepare the authentication.
String usernameAuth = "u";
String passwordAuth = "p";
post.addHeader("Authorization", "Basic " +
Base64.encodeToString((usernameAuth + ":" + passwordAuth).getBytes("UTF-8"),
android.util.Base64.NO_WRAP));
For running this at regular intervals :
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// What you want to do goes here
}
}, 0, REFRESH_TIME);
I hope it helps.
精彩评论