1

我正在尝试访问带有空格的网址:

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()

问题在于“内容类型”中的空格将字符串分隔为两个不同的块。

如何发送此请求?

4

4 回答 4

3

多谢你们,

我找到了另一个(疯狂但有效)的解决方案:

url_string.replace (" ","%20")
于 2014-07-09T08:01:32.777 回答
2

因为其他答案是使用 python 2.x 或 urllib 并且问题标记为urllib3,所以这里有一个适用urllib3于 python 3.x的版本。

将为request您编码网址。如果您出于某种原因需要手动执行此操作,您可以在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)
于 2014-07-09T07:52:23.617 回答
2

使用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)
于 2014-07-09T07:41:37.393 回答
1
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
于 2014-07-09T07:40:46.777 回答