【问题标题】:Receiving Error 415 : Unsupported media type when sending GET request with a REST API接收错误 415:使用 REST API 发送 GET 请求时不受支持的媒体类型
【发布时间】:2015-11-19 11:08:01
【问题描述】:

我创建了一些 python 代码来与 Exact Online 通信,并希望通过使用带有 urllib2 的 python 来发送 GET 和 POST 请求。

现在,当我尝试发送一个简单的 GET 请求时,包括像“接受:应用程序/json”这样的标头,当我在测试应用程序 (SOAP-UI) 中尝试它时,它可以工作

我的python代码如下:

import urllib2, urllib, json, requests, base64

data = urllib.urlencode({
})
request = urllib2.Request(
url="https://start.exactonline.nl/api/v1/"+divis+"/salesorder/SalesOrderLines?access_token=" + access,
data=data)

base64string = base64.encodestring('%s:%s' % (user,password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
request.add_header("Content-Type", "application/json+xml")
request.add_header("Accept", "application/json+xml")

request= urllib2.urlopen(request)
print request_open
response = request_open.read()
print response

这会导致

Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101   5.0\src\debug\tserver\_sandbox.py", line 70, in <module>
File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 45, in retrieve_tokens
File "C:\Python27\Lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\Lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\Lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\Lib\urllib2.py", line 448, in error
return self._call_chain(*args)
File "C:\Python27\Lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\Lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 415: Unsupported Media Type

我已经尝试过使用 Content-Type 和 Accept 以及不使用另一个。所有人都给出了相同的 415 响应。 当我尝试只使用

request.add_header("Content-Type", "application/json")

request.add_header("Content-Type", "application/atom+xml")

我收到以下回复:

urllib2.HTTPError: HTTP Error 400: Bad Request

我认为这可能是这一切的原因。

有人知道如何解决这个问题吗?

也许值得一提的是,当我用另一个应用程序对此进行测试时,响应为Content-Type: application/atom+xml;charset=utf-8

【问题讨论】:

  • 您应该检查响应负载。它可能有关于错误的更多详细信息。此外,您应该使用 python-requests 而不是 urllib2。

标签: python httprequest urllib2 exact-online


【解决方案1】:

我发现一些 Web 服务器要求您发送 User-Agent 标头才能工作。

尝试附加这个:

request.add_header("User-Agent", "what u like")

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 2020-09-25
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2018-10-13
    • 2018-07-25
    相关资源
    最近更新 更多