Reputation: 349
I am trying to read data from this API API Wykazu podatników VAT
Thru HttpWebRequest it's working:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://wl-test.mf.gov.pl:9091/wykaz-podatnikow/api/search/nips/3245174504?date=2019-09-27");
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
Console.WriteLine(reader.ReadToEnd());
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
But when I try it thru WebClient:
var client = new WebClient();
client.Headers.Add("nips", "3245174504");
client.Headers.Add("date", "2019-09-27");
var response = client.DownloadString("https://wl-test.mf.gov.pl:9091/wykaz-podatnikow/api/search/nips/");
Console.WriteLine(response.ToString());
I got this error message:
Unhandled Exception: System.Net.WebException: An exception occurred during a WebClient request. ---> System.ArgumentException: The 'date' header must be modified using the appropriate property or method. Parameter name: name at System.Net.WebHeaderCollection.ThrowOnRestrictedHeader(String headerName) at System.Net.WebHeaderCollection.Add(String name, String value) at System.Net.HttpWebRequest.set_Headers(WebHeaderCollection value) at System.Net.WebClient.CopyHeadersTo(WebRequest request) at System.Net.WebClient.GetWebRequest(Uri address) at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) --- End of inner exception stack trace --- at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) at System.Net.WebClient.DownloadString(Uri address) at System.Net.WebClient.DownloadString(String address)
How should I format the second Date parameter?
Upvotes: 0
Views: 563
Reputation: 608
I would recommend using the newer HTTPClient as it is specifically created for API calls -
using (var x = new HttpClient())
{
var y = x.GetAsync("https://wl-test.mf.gov.pl:9091/wykaz-podatnikow/api/search/nips/3245174504?date=2019-09-27").Result;
var json = y.Content.ReadAsStringAsync().Result;
}
Just to add, please don't use .Result, instead use the async/await operators.
Upvotes: 1
Reputation: 446
Are you mistaking request headers with Query Parameters? if so you might want the following instead:
https://wl-test.mf.gov.pl:9091/wykaz-podatnikow/api/search?nips=3245174504&date=2019-09-27
Upvotes: 0