简体   繁体   中英

WebService Call from .net C# getting error : (502) Bad Gateway

Trying to call WebServices from C# and getting below error:

System.Net.WebException: 'The remote server returned an error: (502) Bad Gateway

Code:

WebRequest request = WebRequest.Create("https://xxxxx/cgi/webservice.pl?function=get_latest_ts_values&site_list=130105B&datasource=AT&varfrom=10.00&varto=10.00&lookback=60&format=csv");
        request.Method = "GET";
        WebResponse response = request.GetResponse();
        using (Stream dataStream = response.GetResponseStream() )
        {
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Console.WriteLine(responseFromServer);
            Console.ReadLine();
        }

But works fine when i use Postman or just copy url in browser and also works fine with below python code:

import requests

dataload = {}
dataurl = "https://xxxxx/cgi/webservice.pl?function=get_latest_ts_values&site_list=130105B&datasource=AT&varfrom=10.00&varto=10.00&lookback=60"
headers = {}
response = requests.request("GET", dataurl, headers=headers, data=dataload)
for dataresp in response:
    print(dataresp)

What am I doing wrong with C# code?

The uri for the WebRequest has the query parameter &format=csv . Maybe this is why you are getting a 502. The Python request is missing that query parameter. Did you try the WebRequest by removing that part?

Could be incorrect content type or user agent having the wrong information. Postman could be setting these values without your knowledge. Might try in the exception seeing if there is aa response stream and read it through a streamreader to see if there is any more information you're not seeing to point you in the correct direction.

Ended up using RestSharp and it works fine. ( https://www.nuget.org/packages/RestSharp )

 string Uri = "https://xxxx/cgi/webservice.pl?xxxx";
 var client = new RestSharp.RestClient(Uri);
 client.Timeout = -1;
 var request = new RestRequest(Method.GET);
 IRestResponse response = client.Execute(request);
 Console.WriteLine(response.Content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM