python - RESTful API 请求适用于 Python 和浏览器,但不适用于 VB.Net
问题描述
我想通过以下调用调用 RESTful API
https://sdw-wsrest.ecb.europa.eu/service/data/EXR/D..EUR.SP00.A?updatedAfter=2018-08-01T07%3A05%3A02%2B07%3A05&startPeriod=2018-08-01&detail=dataonly&dimensionAtObservation=TIME_PERIOD
结果应该是一个包含货币汇率的 XML。
我需要让它在 vb.net 中工作,但它不起作用(不再)。几天前它仍然有效。我使用以下代码:
Try
' define webclient settings
Dim _webClient As System.Net.WebClient = New System.Net.WebClient
' I tried with and without the following line
' _webClient.Headers(HttpRequestHeader.UserAgent) = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36"
Dim link as String = "https://sdw-wsrest.ecb.europa.eu/service/data/EXR/D..EUR.SP00.A?updatedAfter=2018-08-01T07%3A05%3A02%2B07%3A05&startPeriod=2018-08-01&detail=dataonly&dimensionAtObservation=TIME_PERIOD"
Dim sourceString As String = _webClient.DownloadString(link)
Catch ex As Exception
' Error in request url or on the server side
Console.WriteLine(DateTime.Now.ToString("MMM dd hh:mm:ss") & " Error: " & ex.Message)
然后ex.message
包含以下信息:
远程服务器返回错误:(500) Internal Server Error
但是,当复制并粘贴到地址栏和 Python 时,相同的请求在我的浏览器中有效。我使用以下 Python 代码:
import requests
url = 'https://sdw-wsrest.ecb.europa.eu/service/data/EXR/D..EUR.SP00.A?updatedAfter=2018-08-01T07%3A05%3A02%2B07%3A05&startPeriod=2018-08-01&detail=dataonly&dimensionAtObservation=TIME_PERIOD'
response = requests.get(url)
print(response.status_code) #returns 200
VB.Net 代码中的错误是什么?有什么区别?
解决方案
我知道错误是什么。我必须Accept
按如下方式设置标题:
_webClient.Headers(HttpRequestHeader.Accept) = "*/*"
然后它工作。
推荐阅读
- javascript - Javascript按钮幻灯片
- java - 如何在 Log4j2 中自定义或删除默认属性 - JSON 布局
- python - pandas pivot_table 的边距仅垂直聚合
- python - ModuleErrorNotFound:没有名为“nltk”的模块
- postgresql - 在 Postgres 10.6 中,CASE 中不允许设置返回函数
- java - 在根项目中找不到任务“generateApolloSources”
- c++ - 完美转发解释为右值引用
- azure-cosmosdb - 为什么通过 ARM 模板部署 Azure Cosmos DB (SQL API) 需要这么长时间?
- java - 在 Java 中创建随机数生成器 - 每次重置数组
- python - 使用 Python 从文本中提取值