Description An application may need to connect to a resource that is protected using basic HTTP authentication. The following code sample illustrates how to authenticate using basic HTTP authentication from within a BlackBerry smartphone application. For a complete code sample showing how to create an HTTP connection (without authentication), see the httpdemo application included with the BlackBerry® Java® Development Environment. HttpConnection httpConn = null; StreamConnection s = null; boolean keepGoing = true; int dialogResponse; try { s = (StreamConnection)Connector.open("http://mysite.com/myProtectedFile.txt"); httpConn = (HttpConnection)s; while(keepGoing) { int status = httpConn.getResponseCode(); switch (status) { case (HttpConnection.HTTP_OK): //Connection is 200 OK. //Download and process data. keepGoing = false; break; case (HttpConnection.HTTP_UNAUTHORIZED): //Connection is 401 UnAuthorized. //A login and password is required. //Obtain the login information from somewhere. //You could prompt the user for this information or //retrieve this from elsewhere if it is saved within //your application. //Login information is hard coded here for brevity, but //we ask the user if they want to log in. UiApplication.getUiApplication().invokeAndWait(new Runnable() { public void run() { dialogResponse = Dialog.ask (Dialog.D_YES_NO,"Unauthorized Access:/n Do you wish to log in?"); } }); if (dialogResponse == Dialog.YES) { String login = "username:password"; //Close the connection. s.close(); //Encode the login information in Base64 format. byte[] encoded = Base64OutputStream.encode(login.getBytes(), 0, login.length(), false, false); //Open a new connection. s = (StreamConnection)Connector.open("http://mysite.com/myProtectedFile.txt "); httpConn = (HttpConnection)s; //Add the authorized header. httpConn.setRequestProperty("Authorization", "Basic " + new String(encoded)); } else { //Handle failed connection. keepGoing = false; } break; default: //The connection failed for some other reason. //Handle failed connection. keepGoing = false; break; } } //Close the connection. s.close(); } catch (IOException e) { //Handle the exception. }
Implement basic HTTP authentication
最新推荐文章于 2024-05-24 09:06:00 发布