วันพฤหัสบดีที่ 26 มีนาคม พ.ศ. 2552

python http post text stream

ในกรณีที่เราต้องการ post text string หรือ data บางอย่าง เช่น xml information บางอย่าง
ในส่วนของ การ post ส่วนใหญ่จะเป็นในกรณี name:value โดยตัวอย่าง format จะเป็นประมาณ
http://localhost:8080web?name=uname&data=udata
name:value จะเป็น name:uname , data:udata

แต่กรณีที่เราต้องการ post text อย่างเดียว จะเป็นการ post body ตัวอย่างด้านล่าง

http://localhost:8080/web
body = '<xml><auth><user>userxy</user><pass>xxxyyy</pass></auth><data>test data stream.</data></xml>'

data ในส่วนของ body จะไม่ถูกต่อท้าย และจะไม่มี name:value

code ตัวอย่าง

import httplib

def post(url='', data=''):
    print ' url post : %s ' % url
    print ' data post : %s ' % data
    try:
        ufull = url.replace('http://', '')
        x = ufull.find('/')
        h = httplib.HTTP(ufull[:x])
        h.putrequest('POST', ufull[x:])
        h.putheader('content-type', 'text/xml')
        h.putheader('content-length', str(len(data)))
        h.endheaders()
        h.send(data)
        errcode, errmsg, headers = h.getreply()
        res = h.file.read()
    except Exception, ex:
        raise ex
    return res

if '__main__' == __name__:
    u = 'http://localhost:8080/web'
    d = '<xml><auth><user>userxy</user><pass>xxxyyy</pass></auth><data>test data stream.</data></xml>'
    res = post(url=u, data=d)
    print 'response post : %s' % res
---------------------------------

ไม่มีความคิดเห็น: