user1641071
user1641071

Reputation: 385

white spaces in url

I'm trying to access a url with spaces:

url_string = "http://api.company.com/SendMessageXml.ashx?SendXML=<company><User><Username>username</Username><Password>passweord</Password></User><Content Type=sms>.."
with urllib.request.urlopen(url_string) as url:
    s = url.read()

The problem is with the space in "content type" separates the string to two different blocks.

How can I send this request?

Upvotes: 1

Views: 5859

Answers (4)

user1641071
user1641071

Reputation: 385

Thanks guys,

I found another (crazy but working) solution:

url_string.replace (" ","%20")

Upvotes: 3

msvalkon
msvalkon

Reputation: 12077

Because the other answers are either using python 2.x or urllib and the question is tagged for urllib3, here's a version that works with urllib3 on python 3.x.

the request will encode the url for you. If you for some reason need to do this manually, you can find it in urllib3.request.urlencode.

>>> params = {'SendXML': '<company><User><Username>username</Username><Password>passweord</Password></User><Content Type=sms>'}
>>> url = "http://api.company.com/SendMessageXml.ashx"
>>> http = urllib3.PoolManager()
>>> r = http.request('GET', url, params)

Upvotes: 2

user1907906
user1907906

Reputation:

Use urllib.parse.urlencode:

import urllib.parse
query = urllib.parse.urlencode({
  "SendXML":
  "<company><User><Username>username</Username><Password>passweord</Password></User><Content Type=sms>.."
})
urllib.request.urlopen(query)

Upvotes: 2

ssut
ssut

Reputation: 441

import urllib.parse, urllib.request

params = { "SendXML": "<company><User><Username>username</Username><Password>passweord</Password></User><Content Type=sms>.." }
url_string = "http://api.company.com/SendMessageXml.ashx?%s" % (urllib.parse.urlencode(params))
s = ""
with urllib.request.urlopen(url_string) as url:
    s = url.read()

print s

Upvotes: 1

Related Questions