HTTP Basic Authentication认证

来源:互联网 发布:电击棒淘宝怎么搜 编辑:程序博客网 时间:2024/04/26 19:13

 问题:

最近做项目Http请求需要要用到 (HTTP Basic Authentication认证),这里整理了一下以供大家参考

Java代码  收藏代码

  1. 什么是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧。  
  2. 在你访问一个需要HTTP Basic Authentication的URL的时候,如果你没有提供用户名和密码,服务器就会返回401,如果你直接在浏览器中打开,浏览器会提示你输入用户名和密码(google浏览器不会,bug?)。你可以尝试点击这个url看看效果:http://api.minicloud.com.cn/statuses/friends_timeline.xml  
  3. 要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:  
  4. 一是在请求头中添加Authorization:  
  5. Authorization: "Basic 用户名和密码的base64加密字符串"  
  6. 二是在url中添加用户名和密码:  
  7. http://userName:password@api.minicloud.com.cn/statuses/friends_timeline.xml  
  8.   
  9. //需要Base64见:http://www.webtoolkit.info/javascript-base64.html  
  10. function make_base_auth(user, password) {  
  11.   var tok = user + ':' + pass;  
  12.   var hash = Base64.encode(tok);  
  13.   return "Basic " + hash;  
  14. }   
  15.   
  16. var auth = make_basic_auth('QLeelulu','mypassword');  
  17. var url = 'http://example.com';   
  18.   
  19. // 原始JavaScript  
  20. xml = new XMLHttpRequest();  
  21. xml.setRequestHeader('Authorization', auth);  
  22. xml.open('GET',url)   
  23.   
  24. // ExtJS  
  25. Ext.Ajax.request({  
  26.     url : url,  
  27.     method : 'GET',  
  28.     headers : { Authorization : auth }  
  29. });   
  30.   
  31. // jQuery  
  32. $.ajax({  
  33.     url : url,  
  34.     method : 'GET',  
  35.     beforeSend : function(req) {  
  36.         req.setRequestHeader('Authorization', auth);  
  37.     }  
  38. });  
Java代码  收藏代码
  1. <span style="font-family: Verdana, sans-serif; color: #444444;"><span>下面摘录一段 Jsp实现鉴权的代码逻辑</span></span>  
Java代码  收藏代码
  1. <pre class=" 以下是一段Jsp鉴权操作 " name="code"> 以下是一段Jsp鉴权操作   
  2. 1、server发送一个要求认证代码401和一个头信息WWW-authenticate,激发browser弹出一个认证窗口  
  3.  2、server取得browser送来的认证头"Authorization",它是加密的了,要用Base64方法解密,取得明文的用户名和密码  
  4.     
  5. 3、检查用户名和密码,根据结果传送不同的页面</pre>  
  6.    
Java代码  收藏代码
  1. =========Jsp代码===================  
Java代码  收藏代码
  1. <jsp:useBean id="base64" scope="page" class="Base64"/>    
  2. <%     
  3. if(request.getHeader("Authorization")==null){     
  4. response.setStatus(401);     
  5. response.setHeader("WWW-authenticate""Basic realm="unixboy.com"");     
  6. }else{     
  7. String encoded=(request.getHeader("Authorization"));     
  8. String tmp=encoded.substring(6);     
  9. String up=Base64.decode(tmp);     
  10. String user="";     
  11. String password="";     
  12. if(up!=null){     
  13. user=up.substring(0,up.indexOf(":"));     
  14. password=up.substring(up.indexOf(":")+1);     
  15. }     
  16. if(user.equals("unixboy")&&password.equals("123456")){     
  17. //认证成功     
  18. }else{     
  19. //认证失败     
  20. }     
  21. }     
  22. %>   
  23.   
  24. =======Java段代码==================  
  25.   
  26. //消息加解密class     
  27. public class Base64     
  28. {     
  29. /** decode a Base 64 encoded String.    
  30. * <p><h4>String to byte conversion</h4>   
  31. * This method uses a naive String to byte interpretation, it simply gets each    
  32. * char of the String and calls it a byte.</p>   
  33. * <p>Since we should be dealing with Base64 encoded Strings that is a reasonable    
  34. * assumption.</p>   
  35. * <p><h4>End of data</h4>   
  36. * We don′t try to stop the converion when we find the "=" end of data padding char.    
  37. * We simply add zero bytes to the unencode buffer.</p>   
  38. */     
  39. public static String decode(String encoded)     
  40. {     
  41. StringBuffer sb=new StringBuffer();     
  42. int maxturns;     
  43. //work out how long to loop for.     
  44. if(encoded.length()%3==0)     
  45. maxturns=encoded.length();     
  46. else     
  47. maxturns=encoded.length()+(3-(encoded.length()%3));     
  48. //tells us whether to include the char in the unencode     
  49. boolean skip;     
  50. //the unencode buffer     
  51. byte[] unenc=new byte[4];     
  52. byte b;     
  53. for(int i=0,j=0; i<maxturns; i++)     
  54. {     
  55. skip=false;     
  56. //get the byte to convert or 0     
  57. if(i<encoded.length())     
  58. b=(byte)encoded.charAt(i);     
  59. else     
  60. b=0;     
  61. //test and convert first capital letters, lowercase, digits then ′+′ and ′/′     
  62. if(b>=65 && b<91)     
  63. unenc[j]=(byte)(b-65);     
  64. else if(b>=97 && b<123)     
  65. unenc[j]=(byte)(b-71);     
  66. else if(b>=48 && b<58)     
  67. unenc[j]=(byte)(b+4);     
  68. else if(b==′+′)     
  69. unenc[j]=62;     
  70. else if(b==′/′)     
  71. unenc[j]=63;     
  72. //if we find "=" then data has finished, we′re not really dealing with this now     
  73. else if(b==′=′)     
  74. unenc[j]=0;     
  75. else     
  76. {     
  77. char c=(char)b;     
  78. if(c==′ ′ || c==′ ′ || c==′ ′ || c==′ ′)     
  79. skip=true;     
  80. else     
  81. //could throw an exception here? it′s input we don′t understand.     
  82. ;     
  83. }     
  84. //once the array has boiled convert the bytes back into chars     
  85. if(!skip && ++j==4)     
  86. {     
  87. //shift the 6 bit bytes into a single 4 octet word     
  88. int res=(unenc[0] << 18)+(unenc[1] << 12)+(unenc[2] << 6)+unenc[3];     
  89. byte c;     
  90. int k=16;     
  91. //shift each octet down to read it as char and add to StringBuffer     
  92. while(k>=0)     
  93. {     
  94. c=(byte)(res >> k);     
  95. if ( c > 0 )     
  96. sb.append((char)c);     
  97. k-=8;     
  98. }     
  99. //reset j and the unencode buffer     
  100. j=0;     
  101. unenc[0]=0;unenc[1]=0;unenc[2]=0;unenc[3]=0;     
  102. }     
  103. }     
  104. return sb.toString();     
  105. }     
  106.     
  107. /** encode plaintext data to a base 64 string    
  108. * @param plain the text to convert. If plain is longer than 76 characters this method    
  109. * returns null (see RFC2045).    
  110. * @return the encoded text (or null if string was longer than 76 chars).    
  111. */     
  112. public static String encode(String plain)     
  113. {     
  114. if(plain.length()>76)     
  115. return null;     
  116. int maxturns;     
  117. StringBuffer sb=new StringBuffer();     
  118. //the encode buffer     
  119. byte[] enc=new byte[3];     
  120. boolean end=false;     
  121. for(int i=0,j=0; !end; i++)     
  122. {     
  123. char _ch=plain.charAt(i);     
  124. if(i==plain.length()-1)     
  125. end=true;     
  126. enc[j++]=(byte)plain.charAt(i);     
  127. if(j==3 || end)     
  128. {     
  129. int res;     
  130. //this is a bit inefficient at the end point     
  131. //worth it for the small decrease in code size?     
  132. res=(enc[0] << 16)+(enc[1] << 8)+enc[2];     
  133. int b;     
  134. int lowestbit=18-(j*6);     
  135. for(int toshift=18; toshift>=lowestbit; toshift-=6)     
  136. {     
  137. b=res >>> toshift;     
  138. b&=63;     
  139. if(b>=0 && b<26)     
  140. sb.append((char)(b+65));     
  141. if(b>=26 && b<52)     
  142. sb.append((char)(b+71));     
  143. if(b>=52 && b<62)     
  144. sb.append((char)(b-4));     
  145. if(b==62)     
  146. sb.append(′+′);     
  147. if(b==63)     
  148. sb.append(′/′);     
  149. if(sb.length()%76==0)     
  150. sb.append(′ ′);     
  151. }     
  152. //now set the end chars to be pad character if there      
  153. //was less than integral input (ie: less than 24 bits)     
  154. if(end)     
  155. {     
  156. if(j==1)     
  157. sb.append("==");     
  158. if(j==2)     
  159. sb.append(′=′);     
  160. }     
  161. enc[0]=0; enc[1]=0; enc[2]=0;     
  162. j=0;     
  163. }     
  164. }     
  165. return sb.toString();     
  166. }     
  167. }     


给个直观截图示例吧:(不懂得可以留言下方)






注意:




这里的map   是我自己封装 工具类中自定义添加请求头用的,  参考即可

public static byte[] doGet(String url, Map<String, String> headerMap, String proxyUrl, int proxyPort) {byte[] content = null;HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);// getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");if (headerMap != null) {// 头部请求信息if (headerMap != null) {Iterator iterator = headerMap.entrySet().iterator();while (iterator.hasNext()) {Entry entry = (Entry) iterator.next();getMethod.addRequestHeader(entry.getKey().toString(), entry.getValue().toString());}}}if (StringUtils.isNotBlank(proxyUrl)) {httpClient.getHostConfiguration().setProxy(proxyUrl, proxyPort);}// 设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);// postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER , new// DefaultHttpMethodRetryHandler());InputStream inputStream = null;try {if (httpClient.executeMethod(getMethod) == HttpStatus.SC_OK) {// 读取内容inputStream = getMethod.getResponseBodyAsStream();content = IOUtils.toByteArray(inputStream);} else {System.err.println("Method failed: " + getMethod.getStatusLine());}} catch (IOException ex) {ex.printStackTrace();} finally {IOUtils.closeQuietly(inputStream);getMethod.releaseConnection();}return content;}



原创粉丝点击