Android request HTTP basic authentication
asp.net MVC web API实现了一个基于HTTP basic authentication身份验证的RESTful实现。其中的AuthorizeAttribute实现为如下方式:
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 //用户验证逻辑 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作为客户端调用此RESTful API需要如下实现:
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 httpResponse = httpClient.execute(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 // 保存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 }
调用端需要注意的是需要将站点发布出去,android调用端要用192.168.1.100这样的地址去访问,一定不要用localhost这样的地址,谨记!