Search code examples
androidresthttp-authentication

making REST request


I am new to using REST and feel unconfident. So could you help and say what is the best approach to create a REST client to connect to server using SSL and authorization? I am not asking full example, just what library to use or maybe some native library?


Solution

  • You can use the built-in HttpURLConnection class to talk to a restful service. That class also supports https urls, which provide you with SSL encryption. For the authentication, you can use the built in mechanisms.

    For Username+Password or Digest auth, you can just use the java.net.Authenticator, that you may need to extend like this:

    public class AS7Authenticator extends Authenticator {
    
        private String user;
        private String pass;
    
        public AS7Authenticator(String user, String pass) {
            this.user = user;
            this.pass = pass;
            if (this.pass==null)
                this.pass=""; // prevent NPE later
        }
    
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user,pass.toCharArray());
        }
    }
    

    (taken from the JBossAS7 plugin of RHQ)

    For Android versions > 2.3, the HttpUrlConnection seems to be the preferred client by the Android developers anyway.