Android的服务器数据获取 [英] 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;
}
由于服务器有一个登录界面,我不知道如何将它传递。所以,我想帮助的2 thigs: 1 从服务器获取数据和 2 每1或2分钟,我需要刷新我的应用程序,并再次获取。的数据。
Since the server has a logon screen I don't know 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 .
推荐答案
您可以试试这个一职的对象。 pre-先发制人进行身份认证这种方式。
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.
这篇关于Android的服务器数据获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!