Use HTTP authentication

  1. Import the following classes:
    • net.rim.device.api.system.CoverageInfo
    • javax.microedition.io.Connector
    • net.rim.device.api.ui.UiApplication
    • net.rim.device.api.ui.component.Dialog
    • java.lang.String
  2. Import the following interfaces:
    • javax.microedition.io.HttpConnection
    • net.rim.device.api.system.CoverageStatusListener
    • javax.microedition.io.StreamConnection
  3. Use the CoverageInfo class and CoverageStatusListener interface of the net.rim.device.api.system package to verify that the BlackBerry device is in wireless network coverage area.
  4. Invoke Connector.open(), using the HTTP location of the protected resource.
  5. Cast and store the returned object as a StreamConnection.
    StreamConnection s = (StreamConnection)Connector.open("http://mysite.com/myProtectedFile.txt");
    
    
  6. Cast and store the StreamConnection object as an HTTPConnection object.
    HttpConnection httpConn = (HttpConnection)s;
    
  7. Invoke HttpConnection.getResponseCode().
    int status = httpConn.getResponseCode();
    
  8. Create code to manage an unauthorized HTTP connection attempt.
    int status = httpConn.getResponseCode();
    switch (status)
    case (HttpConnection.HTTP_UNAUTHORIZED);
    
  9. Create a run()method and within it implement a dialog object to ask the BlackBerry device user for login information.
    UiApplication.getUiApplication().invokeAndWait(new Runnable())
    {
    public void run()
    {
    dialogResponse = Dialog.ask;
    (Dialog.D_YES_NO,"Unauthorized Access:\n Do you wish to log in?");
    }
    }
    
  10. To process the login information, create code to manage a Yes dialog response.
    1. Retrieve the login information and close the current connection.
      if (dialogResponse == Dialog.YES)
      {String login = "username:password";
      //Close the connection.
      s.close();
      
    2. Encode the login information.
      byte[] encoded = Base64OutputStream.encode(login.getBytes(),
      0, login.length(), false, false);
      
      
  11. Invoke HTTPConnection.setRequestProperty() using the encoded login information to access the protected resource.
    s = (StreamConnection)Connector.open("http://mysite.com/myProtectedFile.txt ");
    httpConn = (HttpConnection)s;
    httpConn.setRequestProperty("Authorization", "Basic " + new String(encoded));
    

Index


Was this information helpful? Send us your comments.