访问需要HTTP Basic Authentication认证的资源的各种语言的实现

无聊想调用下嘀咕的api的时候,发现需要HTTP Basic Authentication,就看了下。

什么是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧。

在你访问一个需要HTTP Basic Authentication的URL的时候,如果你没有提供用户名和密码,服务器就会返回401,如果你直接在浏览器中打开,浏览器会提示你输入用户名和密码(google浏览器不会,bug?)。你可以尝试点击这个url看看效果:http://api.minicloud.com.cn/statuses/friends_timeline.xml

要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:

下面来看下对于第一种在请求中添加Authorization头部的各种语言的实现代码。

先看.NET的吧:

  1.  
  2. string username="username";
  3. string password="password";
  4. //注意这里的格式哦,为 "username:password"
  5. string usernamePassword = username + ":" + password;
  6. CredentialCache mycache = new CredentialCache();
  7. mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
  8. myReq.Credentials = mycache;
  9. myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
  10.  
  11. WebResponse wr = myReq.GetResponse();
  12. Stream receiveStream = wr.GetResponseStream();
  13. StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
  14. string content = reader.ReadToEnd();

你当然也可以使用HttpWebRequest或者其他的类来发送请求。

然后是Python的:

  1.  
  2. import urllib2
  3. import sys
  4. import re
  5. import base64
  6. from urlparse import urlparse
  7.  
  8. theurl = 'http://api.minicloud.com.cn/statuses/friends_timeline.xml'
  9.  
  10. username = 'qleelulu'
  11. password = 'XXXXXX' # 你信这是密码吗?
  12.  
  13. base64string = base64.encodestring(
  14. '%s:%s' % (username, password))[:-1] #注意哦,这里最后会自动添加一个\n
  15. authheader = "Basic %s" % base64string
  16. req.add_header("Authorization", authheader)
  17. try:
  18. handle = urllib2.urlopen(req)
  19. except IOError, e:
  20. # here we shouldn't fail if the username/password is right
  21. print "It looks like the username or password is wrong."
  22. sys.exit(1)
  23. thepage = handle.read()
 

再来是PHP的:

  1.  
  2. <?php
  3. $fp = fsockopen("www.mydomain.com",80);
  4. fputs($fp,"GET /downloads HTTP/1.0");
  5. fputs($fp,"Host: www.mydomain.com");
  6. fputs($fp,"Authorization: Basic " . base64_encode("user:pass") . "");
  7. fpassthru($fp);
  8. ?>
 

还有flash的AS3的:

  1.  
  2. import mx.rpc.events.FaultEvent;
  3. import mx.rpc.events.ResultEvent;
  4. import mx.utils.Base64Encoder;
  5. import mx.rpc.http.HTTPService;
  6. URLRequestDefaults.authenticate = false;//设默认为false,否则用户较验错误时会弹出验证框
  7.  
  8. private var result:XML;
  9. private function initApp():void
  10. {
  11. var base64enc:Base64Encoder = new Base64Encoder;
  12. base64enc.encode("user:password"); //用户名和密码需要Base64编码
  13. var user:String = base64enc.toString();
  14.  
  15. var http:HTTPService = new HTTPService;
  16. http.addEventListener(ResultEvent.RESULT,resultHandler);//监听返回事件
  17. http.addEventListener(FaultEvent.FAULT,faultHandler); //监听失败事件
  18. http.resultFormat = "e4x";//返回格式
  19. http.url = "http://api.digu.com/statuses/friends_timeline.xml"; 以嘀咕网的API为列
  20. http.headers = {"Authorization":"Basic " + user};
  21. http.send();
  22. }
  23. private function resultHandler(e:ResultEvent):void
  24. {
  25. result = XML(e.result);
  26. test.dataProvider = result.status;//绑定数据
  27. }
  28. private function faultHandler(e:ResultEvent):void
  29. {
  30. //处理失败
  31. }
 

还有Ruby On Rails的:

  1.  
  2. class DocumentsController < ActionController
  3. before_filter :verify_access
  4.  
  5. def show
  6. @document = @user.documents.find(params[:id])
  7. end
  8.  
  9. # Use basic authentication in my realm to get a user object.
  10. # Since this is a security filter - return false if the user is not
  11. # authenticated.
  12. def verify_access
  13. authenticate_or_request_with_http_basic("Documents Realm") do |username, password|
  14. @user = User.authenticate(username, password)
  15. end
  16. end
  17. end
 

汗,忘记JavaScript的了:

  1.  
  2. //需要Base64见:http://www.webtoolkit.info/javascript-base64.html
  3. function make_base_auth(user, password) {
  4. var tok = user + ':' + pass;
  5. var hash = Base64.encode(tok);
  6. return "Basic " + hash;
  7. }
  8.  
  9. var auth = make_basic_auth('QLeelulu','mypassword');
  10. var url = 'http://example.com';
  11.  
  12. // 原始JavaScript
  13. xml = new XMLHttpRequest();
  14. xml.setRequestHeader('Authorization', auth);
  15. xml.open('GET',url)
  16.  
  17. // ExtJS
  18. Ext.Ajax.request({
  19. url : url,
  20. method : 'GET',
  21. headers : { Authorization : auth }
  22. });
  23.  
  24. // jQuery
  25. $.ajax({
  26. url : url,
  27. method : 'GET',
  28. beforeSend : function(req) {
  29. req.setRequestHeader('Authorization', auth);
  30. }
  31. });

这里提醒下,HTTP Basic Authentication对于跨域又要发送post请求的用JavaScript是实现不了的(注:对于Chrome插件这类允许通过AJAX访问跨域资源的,是可以的)。。

HTTP Basic Authentication认证的各种语言 后台用的的更多相关文章

  1. 访问需要HTTP Basic Authentication认证的资源的各种开发语言的实现

    什么是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧. 在你访问一个需要H ...

  2. HTTP Basic Authentication认证

    http://smalltalllong.iteye.com/blog/912046 ******************************************** 什么是HTTP Basi ...

  3. HttpClient 三种 Http Basic Authentication 认证方式,你了解了吗?

    Http Basic 简介 HTTP 提供一个用于权限控制和认证的通用框架.最常用的 HTTP 认证方案是 HTTP Basic authentication.Http Basic 认证是一种用来允许 ...

  4. HTTP Basic Authentication认证(Web API)

    当下最流行的Web Api 接口认证方式 HTTP Basic Authentication: http://smalltalllong.iteye.com/blog/912046 什么是HTTP B ...

  5. 访问需要HTTP Basic Authentication认证的资源的c#的实现 将账号密码放入url

    string url = ""; string usernamePassword = username + ":" + password; HttpWebReq ...

  6. 访问需要HTTP Basic Authentication认证的资源的c#的实现

    string username="username"; string password="password"; //注意这里的格式哦,为 "usern ...

  7. HTTP Basic Authentication

    Client端发送请求, 要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:1. 在请求头中添加Authorization:    Authoriz ...

  8. Edusoho之Basic Authentication

    通过如下代码,可以正常请求并获取对应的数据: curl -X POST -H "Accept:application/vnd.edusoho.v2+json" -H "A ...

  9. Atitit HTTP 认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结

    Atitit HTTP认证机制基本验证 (Basic Authentication) 和摘要验证 (Digest Authentication)attilax总结 1.1. 最广泛使用的是基本验证 ( ...

随机推荐

  1. Xcode 注释工具的使用

    1:Xcode 8之后 Goodbye World In Xcode 8, Apple integrated a comment documentation generator plugin, whi ...

  2. Launchpad灰色图标怎么删除?重置Launchpad教程

    打开终端,第一步输入:defaults write com.apple.dock ResetLaunchPad -bool true 按下return键 第二步输入:killall Dock 按下re ...

  3. glib实践篇:接口定义与实现

    前言: 在上一篇讲解了基于glib实现抽象和继承后,当然这篇就得讲讲接口类型啦! 在JAVA中接口更多的弥补了其单继承所带来的缺陷,使其能够扩展很多功能,同时又不破坏它的结构.其实接口就是一种协议,在 ...

  4. sparksql中行转列

    进入sparksql beeline -u "jdbc:hive2://172.16.12.46:10015" -n spark -p spark -d org.apache.hi ...

  5. maven项目如何引用本地的jar包

    下载该jar包到本地(如下载目录结构为:D:\Users\lu.wang\Downloads\searchservice\searchservice\jar\ttd.search.searchserv ...

  6. C语言温度

    #include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or a ...

  7. HTTP 错误 403.14 - Forbidden的解决办法

    错误: HTTP 错误 403.14 - ForbiddenWeb 服务器被配置为不列出此目录的内容.   原因: 出现这个错误,是因为默认文档中没有增加index.aspx导致的. 解决方法: 打开 ...

  8. HTTP 错误 404.8 - Not Found

    HTTP 错误 404.8 - Not Found请求筛选模块被配置为拒绝包含 hiddenSegment 节的 URL 中的路径. 详细错误信息模块 RequestFilteringModule 通 ...

  9. Android_AndroidStudio配置

    IDE降低了程序编译的门槛, 让Android程序的编译和运行变得简单易操作. 但无论Eclipse还是Android Studio, IDE都不是非常智能和可靠的, 总会出大大小小的问题. 很多时候 ...

  10. MocorDroid编译工程快速建立编译环境

    function sprdLunch(){    declare -a arrProj    arrProj=`find out/target/product -name previous_build ...