我试图用python编写一个简单的Http代理。 这是我的代码:
import BaseHTTPServer
import urllib2
import threading
HOST_NAME="localhost"
PORT_NUMBER=9090
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def handle_get_async(self):
opener = urllib2.build_opener()
#opener.addheaders = self.headers.items()
response = opener.open(self.path)
response_content=response.read()
response.close()
self.send_response(200)
self.send_header("Content-type",response.info().type)
self.end_headers()
self.wfile.write(response_content)
def handle_head_async(s):
s.send_responde(200)
s.send_Header("Content-type","text/html")
s.end_headers()
def do_HEAD(s):
thread = threading.Thread(target=self.handle_head_async)
thread.start()
thread.join()
def do_GET(self):
thread = threading.Thread(target=self.handle_get_async)
thread.start()
thread.join()
if __name__ == '__main__':
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), RequestHandler)
httpd.serve_forever()
所以一切正常,但是当我使用opener.addheaders = self.headers.items()复制浏览器发送的标题并将其复制到新请求时,我只是在浏览器中看到奇怪的字符,如下所示:
Ô½Yo#I¶&安培;ø^¿AO«:¯”)JU-PJn'(q'ZCQ ^ NW#ÝEßä)**€z`€AEI€™ - <žy¨Ûfè-Æ4ptþ‰ê· ÂEãöüŒ9ÇÌÝé\œŠHeõB$ Y-SZ}fvì~Ùq³Ÿ¾«uªƒÛnS];þÍOøÅi¢1&GT;âeÂsª|广告‰MSAS和;:?!Îo~ƒÃcb“ECéÄ9Im‡¸G¼çŽEž;8þÉ'lÕrGž¹ªipÄ~žhž£I»ÃÀáŽO |½3mNæTƒw¥÷‡‡#&gt;?©jsælß&amp;žj“|ø&lt;ßý¸¶óþïêÆôï&gt;ìw?Í!áñÈO?ÿøÇŸ‡;ðâ?...¢|äÅñÉR-”¸æ“ü¾|óðỔ :ñHEÎ[c~×G~»ò»³→Ñq34aAÉ?8°õ?8‰äHö~?vÙ$ v“9-~O&lt; {”Èø?S‡Ä
有人知道这个问题吗?