Reputation: 1
I have a problem that I've been working on for a long time! I want to send an API request to the Guesty service (link to the documentation: https://docs.guesty.com/#introduction), and get JSON.
string address = "https://api.guesty.com/api/v2/" + path + "?skip=" + sk + "&limit=100";
string Storage = "*****" + storage + ".json";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(address);
webRequest.KeepAlive = false;
webRequest.ProtocolVersion = HttpVersion.Version11;
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11; // here I tried all sorts of combinations, including SecurityProtocolType.Tls and SecurityProtocolType.SystemDefault
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.ContentLength = 0;
string autorization = extension.GuestyKeyAPI + ":" + extension.GuestySecret; //extension - this is what comes from the form fields
byte[] binaryAuthorization = Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
webRequest.Headers.Add("Authorization", autorization);
using (WebResponse response = (HttpWebResponse)webRequest.GetResponse()) // This is where the error message appears
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
using (StreamWriter writer = new StreamWriter(Storage))
{
string s = reader.ReadToEnd();
writer.WriteLine(s);
reader.Close();
writer.Close();
}
}
}
string jsonString = File.ReadAllText(Storage);
return jsonString;
But the most annoying thing is not this, if you click on Continue in VS, then re-click on Send in the form, then everything suddenly works, JSON comes. Also checked on another computer, there is the same situation (all antivirus programs are disabled). We also tried using HttpClient, but the error is the same. How do I solve this problem? Thank you in advance for any help!
Upvotes: 0
Views: 212
Reputation: 19996
Change this:
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
To this:
using (StreamReader reader = new StreamReader(response.GetResponseStream(),
Encoding.UTF8, true, 1024,
true)) // Leave stream open!
This prevents the using
statement from disposing (closing) the response stream. See StreamReader.cs(258). I believe the exception you are seeing originates in HttpWebRequest.cs(4321).
Upvotes: 1