2009年03月24日

加入了HTTP代理的支持,HTTP发送方式中。TCP发送方式也可能会加上吧,使用SocksiPy这个库吧,有时间再说。

的时候发现urllib2的一个问题:
先看下面这段代码:

:
  1. import urllib2
  2. headers = [("Content-Type","application/oct-stream"),]
  3. opener = urllib2.build_opener()
  4. opener.addheaders = headers
  5. urllib2.install_opener(opener)
  6. print "after install_opener"
  7.  
  8. ret = opener.open('http://www.dict.cn',data="word=ss")
  9. print ret.read()

抓包发现发送的内容为:

POST / HTTP/1.1
Accept-Encoding: identity
Content-Length: 7
Host: www.dict.cn
Content-Type: application/x-www-form-urlencoded
Connection: close

word=ss

这里我在代码里已经指定了HTTP的header: Content-Type,但是发出去的时候却被改变了。

通过分析urllib2的代码,找到:

:
  1. if request.has_data():  # POST
  2.     data = request.get_data()
  3.     if not request.has_header('Content-type'):
  4.         request.add_unredirected_header(
  5.             'Content-type',
  6.             'application/x-www-form-urlencoded')
  7.     if not request.has_header('Content-length'):
  8.          request.add_unredirected_header(
  9.            'Content-length', '%d' % len(data))
  10.  
  11. scheme, sel = splittype(request.get_selector())
  12. sel_host, sel_path = splithost(sel)
  13. if not request.has_header('Host'):
  14.     request.add_unredirected_header('Host', sel_host
  15.     or host)
  16.     for name, value in self.parent.addheaders:
  17.     #这里的parent是opener对象
  18.     name = name.capitalize()
  19.     if not request.has_header(name):
  20.         request.add_unredirected_header(name, value)

urllib2发现如果是POST数据的话自己添加了Content-Type,接着才去追加opener对象中的headers,这时已经有Content-Type了,所以opener对象增加的Content-Type就无效了。

解决办法是创建request对象,在request对象中设置Content-Type:

request = urllib2.Request(url,headers=headers,data=body)

不知道是上面的示例代码写法不规范呢?还是算的一个小问题呢?

最近发现周董的不少歌挺好听,于是找个脚本来下载周董的歌(从百度mp3中), getsong就进入了眼的视野,不过不支持下载某个歌手的全部歌曲,俺自己加上去,正在下载周董的歌:

[cocobear@cocobear ]$ ./.py -a 周杰伦
正在下载第1首(共104首) 歌手:周杰伦 曲名:她的睫毛
已经成功下载《周杰伦 - 她的睫毛》
.......

不过这会儿断了,好像又有bug了,今天就不折腾了,明天再整整吧,看书,睡觉了。

标签 :

随机日志

8 楼了已经

  • 草儿写于09年03月25日

    靠,现在你真勤快。

  • Sutra写于09年03月25日

    不知道删除好友功能是不是必须的。因为听说有个好友人数上限问题。

  • cocobear写于09年03月25日

    这个和发短信没什么关系啊,你别加那么多人就行了啊.

  • xia_chip写于09年03月26日

    要是做个UI界面就更加爽了,最近也在研究蟒蛇!

  • cocobear写于09年03月27日

    UI界面是指getsong还是PyFetion呢?
    蟒蛇有毒,小心中毒!

  • kongove写于09年05月09日

    这个getsong很好用~我和张斌正在读源码~

  • admin写于09年07月14日

    请问最新版的PyFetion在哪里下载呢?

  • cocobear写于09年07月14日

    code.google.com/p/pytool/

发表评论

在下面加入你的评论,或者 trackback 从你的博客站点。 订阅本文的评论。

:

:

:

«
»