Troubleshooting guide

123
7: Creating connections
Code sample: Using HTTP authentication to connect to a protected Internet resource
Example: Using HTTP authentication to connect to a protected Internet resource
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)
Retrieve login information from a
BlackBerry device user.
1. Create code that manages an unauthorized HTTP connection attempt.
int status = httpConn.getResponseCode();
switch (status)
case (HttpConnection.HTTP_UNAUTHORIZED):
2. 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?");
}
}
Process the response of the BlackBerry
device user.
1. Create code that manages a Yes dialog response.
2. Retrieve the login information and close the current connection.
if (dialogResponse == Dialog.YES)
{String login = "username:password";
//Close the connection.
s.close();
3. Encode the login information.
byte[] encoded = Base64OutputStream.encode(login.getBytes(), 0,
login.length(), false, false);
Use the BlackBerry device user login
information to access the protected
resource.
> Open a new HTTPConnection and add the authorization header by invoking
HTTPConnection.setRequestProperty()using the encoded login information.
s = (StreamConnection)Connector.open("http://mysite.com/
myProtectedFile.txt ");
httpConn = (HttpConnection)s;
httpConn.setRequestProperty("Authorization", "Basic " + new
String(encoded));
Task Steps