Downloading data on an Android server

I want to get some data from a server protected by username and password. I know both the username and password. Since the server is in real time, the data continues to change. I need to receive data every minute to update the status of the application. The only function I know that can extract data and convert it to a string:

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 login screen, I do not know how to get through it. So, I would like to help with 2 tigs: 1. receive data from the server and 2. every 1 or 2 minutes. I need to update my application and get the data again.

0
source share
1 answer

You can try this for a post object. Proactive authentication is performed 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)); 

To run this at regular intervals:

 mTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // What you want to do goes here } }, 0, REFRESH_TIME); 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1386188/


All Articles