Asp.net MVC web API implements a restful implementation based on HTTP Basic Authentication authentication. The authorizeattribute is implemented as follows:
1 Public Class Httpbasicauthorizeattribute: system. Web. http. authorizeattribute 2 { 3 Public Override Void Onauthorization (system. Web. http. controllers. httpactioncontext actioncontext) 4 { 5 If (Actioncontext. Request. headers. Authorization! = Null ) 6 { 7 String Userinfo = Encoding. Default. getstring (convert. frombase64string (actioncontext. Request. headers. Authorization. Parameter )); 8 // User verification Logic 9 If ( String . Equals (userinfo, String . Format ( " {0 }:{ 1} " , " Hello " , " 123456 " ))) 10 { 11 Isauthorized (actioncontext ); 12 } 13 Else 14 { 15 Handleunauthorizedrequest (actioncontext ); 16 } 17 } 18 Else 19 { 20 Handleunauthorizedrequest (actioncontext ); 21 } 22 } 23 24 Protected Override Void Handleunauthorizedrequest (system. Web. http. controllers. httpactioncontext actioncontext) 25 { 26 VaR Challengemessage = New System. net. http. httpresponsemessage (system. net. httpstatuscode. Unauthorized ); 27 Challengemessage. headers. Add ( " WWW-Authenticate " , " Basic " ); 28 Throw New System. Web. http. httpresponseexception (challengemessage ); 29 } 30 }
Android needs the following implementation to call this restful API as a client:
1 Public Static String invoke (string actionname ){ 2 String result = Null ; 3 Try { 4 String url = server_url + actionname + "/" ; 5 Log. D (TAG, "url is" + URL ); 6 7 Httpget httpreq = New Httpget (URL ); 8 Httpreq. addheader (basicscheme. Authenticate ( 9 New Usernamepasswordcredentials ("hello", "123456" ), 10 "UTF-8 ", False )); 11 Defaulthttpclient httpclient = New Defaulthttpclient (); 12 Httpresponse = Httpclient.exe cute (httpreq ); 13 14 Stringbuilder builder = New Stringbuilder (); 15 Bufferedreader reader = New Bufferedreader ( New Inputstreamreader ( 16 Httpresponse. getentity (). getcontent ())); 17 For (String S = reader. Readline (); s! = Null ; S = Reader. Readline ()){ 18 Builder. append (s ); 19 } 20 Result = Builder. tostring (); 21 Log. D (TAG, "result is (" + Result + ")" ); 22 23 // Save cookie 24 Cookiestore = (Abstracthttpclient) httpclient). getcookiestore (); 25 } Catch (Exception e ){ 26 Log. E (TAG, E. tostring ()); 27 } 28 Log. D (TAG, "over" ); 29 Return Result; 30 }
The caller must note that the website must be released. The Android caller must use an address like 192.168.1.100 to access the website. Do not use an address like localhost. Remember!