如何使用urllib2发送数据和自定义标头

时间:2013-04-23 10:49:05

标签: python json urllib2 urllib

您好我正在使用urrlib2将一些数据和自定义标头发送到链接。我得到500内部服务器错误。我已经联系了该服务,他们说数据(json数据)是正确的,但我的python代码中有一些错误。我究竟做错了什么 ? 以下是代码。

import urllib2,urllib
import json

PREPAYMENT_URL = "https://services.gharpay.in/rest/GharpayService/" 
PREPAYMENT_USERNAME = "somename"
PREPAYMENT_PASSWORD = "somepass"

data = {
 "customerDetails":{
              "address": "ads",
              "contactNo": "9663924147",
              "email": "a@c.com",
              "firstName": "akash",
              "lastName": "deshpande",
              "prefix": "Mr."
            },

"orderDetails" : {
              "pincode": "411036",
              "clientOrderID": "21234",
              "deliveryDate": "13-10-2013",
              "orderAmount": "123",
              "clientComments": "please be carefull",
              "paymentMode": "Cash",
              "productDetails": {
              "productID": "21334",
              "productQuantity": "1",
              "unitCost": "123",
              "productDescription": "tshirt"
              },
              "templateID": ""
             },

}

def create(request): 

    function = 'createOrder'
    url = PREPAYMENT_URL
    url = url+ function
    headers= {'username':PREPAYMENT_USERNAME,'password':PREPAYMENT_PASSWORD,'Content-type':'application/json'}
    data1 = urllib.urlencode(data)
    req = urllib2.Request(url,data1,headers)
    try:
        contents = urllib2.urlopen(req).read()
    except urllib2.HTTPError as e:
        error_message = e.read()
        print error_message # this error message is being printed. It is showing 500 error.

1 个答案:

答案 0 :(得分:1)

您的代码非常完美,除了一个细微的细节:

  

标题应为内容类型,而不是内容类型

也许尝试更改此标题,让我知道它是否有效!