Search code examples
pythonurllib2

Creating xml request using urllib2


I need to create request to access to the XML services, it should be processed through a HTTP. Ass says in documentation I have to send "4 associated parameters and this parameters will work as identification and will provide the request". This parameters should look like strings:

"codes=12345"
"user=user12345"
"password=pass12345"
"partner=part12345"

According documentation i have two systems for sending the XML file of the request:

1 Through an URL coded in MIME format application/x-www-form- urlencoded: URL (“urlfile”)

2 By entering the data directly in a variable, coded in MIME format application/x-www-form-urlencoded: Directly in a variable (“xml”).

According to this my request data looks like this:

data='
   <?xml version="1.0" encoding="ISO-8859-1" ?>
   <!DOCTYPE petition SYSTEM "http://xml.example.com/xml/dtd/xml.dtd">
   <petition>
      <number>Country request</number>
      <partner>Company</partner>
      <type>5</type>
   </petition>'

I create this request using python library urllib2. So here is my code:

request = urllib2.Request(url,  data)
request.add_header("codes=12345", "user=user12345", "password=pass12345", "partner=part12345")

But i got an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add_header() takes exactly 3 arguments (5 given)

So i changed header on this:

header = {'codes':'12345','user':'user12345','password':'pass12345','partner':'part12345'}

And this is how looks like my code after that:

request = urllib2.Request(url, data, header)
response_xml = urllib2.urlopen(request)
response = response_xml.read()
print(response)

But I got response such if i not authenticated user. What i'm doing wrong? Thank You!


Solution

  • Try this:

    from urllib  import urlencode
    from urllib2 import urlopen
    
    args = {'codes':'12345','user':'user12345','password':'pass12345','partner':'part12345'}
    conn = urlopen(url,urlencode(args))
    data = conn.read()
    conn.close()
    print(data)