0

I'm encountering this message upon WebClient request to the API in C# using the GET method, did I miss something on my code? but when I use the POST method it shows the same output when I test it on PostMan which is the error because POST is not the method to use in this link

Here is my code.

 [WebMethod]
public string HelloWorld()
{
    string module = "/heartbeat";
    string method = "GET";
    string link = sandboxURL;

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // 3072 is SecurityProtocol.Tls12
    System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };

    var response = "";
    string body = "";
    var _link = link + module;
    using (var client = new WebClient())
    {
        try
        {
            client.Headers.Add("Content-Type:application/json");
            client.Headers.Add("Authorization", "Bearer "+ JWTToken);

            //var url = new Uri(_link);

            response = client.UploadString(_link, method, body);
        }
        catch(WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
                var statusCode = (int)wrsp.StatusCode;
                var msg = wrsp.StatusDescription;

                Stream stream = wrsp.GetResponseStream();

                byte[] data = new byte[4096];
                int read;
                StringBuilder sb = new StringBuilder();
                while ((read = stream.Read(data, 0, data.Length)) > 0)
                {
                    sb.Append(ASCIIEncoding.ASCII.GetString(data));
                }
            }
        }
    }

        return response;
}
Cleptus
  • 3,446
  • 4
  • 28
  • 34
  • I guess that if you specify a `Content-Type`, it would expect a content (a body in your request) and that conflict with your GET verb. Try just commenting that line. IMHO you should not say what type of content you want to retrieve, because not always you will get it (you could expect a JSON response but get plain HTML because of a 404) – Cleptus May 08 '20 at 06:35
  • As a suggestion, when that code goes to production you should consider validating the server certificate because of security reasons. – Cleptus May 08 '20 at 06:37

0 Answers0