在python中使用套接字的HTTP基本身份验证 [英] HTTP basic authentication using sockets in python

查看:105
本文介绍了在python中使用套接字的HTTP基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用python中的基本http auth通过套接字连接到服务器.我不想使用urllib/urllib2等,因为我的程序执行了一些底层套接字I/O操作

How to connect to a server using basic http auth thru sockets in python .I don't want to use urllib/urllib2 etc as my program does some low level socket I/O operations

推荐答案

最简单的开始可能是使用makefile()获取套接字的更简单的类似于文件的接口.

Probably the easiest place to start is using makefile() to get a simpler file-like interface to the socket.

import socket, base64

host= 'www.example.com'
path= '/'
username= 'fred'
password= 'bloggs'
token= base64.encodestring('%s:%s' % (username, password)).strip()

lines= [
    'GET %s HTTP/1.1' % path,
    'Host: %s' % host,
    'Authorization: Basic %s' % token,
    'Connection: close',
]

s= socket.socket()
s.connect((host, 80))
f= s.makefile('rwb', bufsize=0)
f.write('\r\n'.join(lines)+'\r\n\r\n')
response= f.read()
f.close()
s.close()

如果您需要解释返回的响应以选择HTML或auth所需的标头,并处理重定向,错误,传输编码等,那么您将需要做的工作要多得多. HTTP可能很复杂!确定要使用低级套接字吗?

You'll have to do a lot more work than that if you need to interpret the returned response to pick out the HTML or auth-required headers, and handle redirects, errors, transfer-encoding and all that right. HTTP can be complex! Are you sure you need to use a low-level socket?

这篇关于在python中使用套接字的HTTP基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆