访问需要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的吧:


string username="username";
string password="password";
//注意这里的格式哦,为 "username:password"
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword))); WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();

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

然后是Python的:


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

再来是PHP的:


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

还有flash的AS3的:


import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.Base64Encoder;
import mx.rpc.http.HTTPService;
URLRequestDefaults.authenticate = false;//设默认为false,否则用户较验错误时会弹出验证框 private var result:XML;
private function initApp():void
{
var base64enc:Base64Encoder = new Base64Encoder;
base64enc.encode("user:password"); //用户名和密码需要Base64编码
var user:String = base64enc.toString(); var http:HTTPService = new HTTPService;
http.addEventListener(ResultEvent.RESULT,resultHandler);//监听返回事件
http.addEventListener(FaultEvent.FAULT,faultHandler); //监听失败事件
http.resultFormat = "e4x";//返回格式
http.url = "http://api.digu.com/statuses/friends_timeline.xml"; 以嘀咕网的API为列
http.headers = {"Authorization":"Basic " + user};
http.send();
}
private function resultHandler(e:ResultEvent):void
{
result = XML(e.result);
test.dataProvider = result.status;//绑定数据
}
private function faultHandler(e:ResultEvent):void
{
//处理失败
}
 

还有Ruby On Rails的:


class DocumentsController < ActionController
before_filter :verify_access def show
@document = @user.documents.find(params[:id])
end # Use basic authentication in my realm to get a user object.
# Since this is a security filter - return false if the user is not
# authenticated.
def verify_access
authenticate_or_request_with_http_basic("Documents Realm") do |username, password|
@user = User.authenticate(username, password)
end
end
end
 

汗,忘记JavaScript的了:


//需要Base64见:http://www.webtoolkit.info/javascript-base64.html
function make_base_auth(user, password) {
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
} var auth = make_basic_auth('QLeelulu','mypassword');
var url = 'http://example.com'; // 原始JavaScript
xml = new XMLHttpRequest();
xml.setRequestHeader('Authorization', auth);
xml.open('GET',url) // ExtJS
Ext.Ajax.request({
url : url,
method : 'GET',
headers : { Authorization : auth }
}); // jQuery
$.ajax({
url : url,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
}
});

这里提醒下,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. 安装windows后grub的恢复

    问题: 原本是:双系统(linux和windows),后来换windows版本覆盖了grub2 解决方法: 进入windows后下载并安装EasyBCD并添加grub2的选项,重启看见了熟悉的启动项, ...

  2. spring boot maven 插件

    spirng boot 需要使用专用maven插件打包,才能打包.引入如下. <build>        <plugins>            <plugin> ...

  3. 基于Unity的Profiler性能分析

    A. WaitForTargetFPS:       Vsync(垂直同步)功能所,即显示当前帧的CPU等待时间    B. Overhead:       Profiler总体时间-所有单项的记录时 ...

  4. iOS中的布局

    1.UIView 有三个比较重要的布局属性: frame , bounds 和 center , CALayer 对应地叫做 frame , bounds 和 position .为了能清楚区分,图层 ...

  5. VM虚拟机的配置文件(.vmx)损坏修复

    来源://http://blog.csdn.net/houffee/article/details/18398603 VM虚拟机中使用.vmx文件保存虚拟机的所有软硬件配置,如果意外损坏的话将会出现不 ...

  6. C++内存池

    内存池是一种内存分配方式.通常我们习惯直接使用new.malloc等API申请分配内存,这样做的缺点在于:由于所申请内存块的大小不定,当频繁使用时会造成大量的内存碎片.并由于频繁的分配和回收内存会降低 ...

  7. react 学习与使用记录

    相关技术:webpack+react+react-router+redux+immutable 郭永峰react学习指南 1.git bash--windows命令行工具 --教程 下载地址 2. i ...

  8. Xcode使用小结2

    刷新时间慢的时候用timer定时器 以下内容为借用,作者:FlyElephant出处:http://www.cnblogs.com/xiaofeixiang iOS开发-NSOperation与GCD ...

  9. C#+ArcEngine中com对象的释放问题

    1.问题描述 最近在写C#下AE的开发,在循环获取数据并修改时碰到了两个问题"超出系统资源"和"超出打开游标最大数":在网上看了一些资料,发现都是说在循环中没有 ...

  10. BigDecimal-解决商业计算

    1.String to BigDecimal String amtStr = "1234.56"; BigDecimal amtBD = new BigDecimal(amtStr ...