[转]Implement basic HTTP authentication – 千丝海阁

首页 » 黑莓开发 » [转]Implement basic HTTP authentication

[转]Implement basic HTTP authentication

1417 0

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. k
eepGoing = false; break;
}
}
//Close the connection.
s.close();
} catch (IOException e) {
//Handle the exception.
}

文章评分1次,平均分5.0



上一篇:英文100句打字练习1.31 for blackberry
下一篇:[转]j2me如何上传文件

本文原始地址:http://www.tiandiyoyo.com/2010/12/%e8%bd%acimplement-basic-http-authentication/
本站所有文章,除了特别注明外,均为本站原创,转载请注明出处来自www.tiandiyoyo.com

您可能还会对以下文章感兴趣:

    没有相关的文章

评论前先开启评论开关: