首页 > 解决方案 > 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 代码中的错误是什么?有什么区别?

标签: pythonvb.netrest

解决方案


我知道错误是什么。我必须Accept按如下方式设置标题:

_webClient.Headers(HttpRequestHeader.Accept) = "*/*"

然后它工作。


推荐阅读