HTTPS呼叫未连接到服务器 [英] Https calls are not connecting to server

查看:83
本文介绍了HTTPS呼叫未连接到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Visual Studio 2017中使用 Windows服务。在其余api的调用中,调试代码时会获取异常。有时在出现异常之后,前2 3个调用会起作用。

I am working on Windows Service in visual studio 2017. In the rest api's call, getting exceptions while debugging code. Sometimes first 2 3 calls working after that getting exceptions.


System.Net.WebException:'远程服务器返回错误:(503)
服务器不可用。'

System.Net.WebException: 'The remote server returned an error: (503) Server Unavailable.'

远程服务器返回错误:(429)

The remote server returned an error: (429)

无法连接到远程服务器

从Postman调用相同的api时,成功获得响应。

这是我的代码

private void timer1_Tick(object sender, ElapsedEventArgs e)
{
    WriteToFile("timer1_Tick method called..");
try
{
    string jsonString = "";
    string jsonstring2 = "";
    string prodfetchurl = HOST;
    var req = WebRequest.Create(prodfetchurl) as HttpWebRequest;
    req.Method = "GET";
    InitializeRequest(req);
    req.Accept = MIME_TYPE;
    //System.Threading.Thread.Sleep(5000);
    var response = (HttpWebResponse)req.GetResponse();
    WriteToFile("First service called...");
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        StreamReader responseReader = new StreamReader(responseStream);
        jsonString = responseReader.ReadToEnd();
    }
    var deserialsseobj = JsonConvert.DeserializeObject<ProductList>(jsonString).Products.Where(i => i.Failed > 0).ToList();
    foreach (var a in deserialsseobj)
    {
        var pid = a.ID;
        string url = FailedDevicesUrl + pid.Value + "/failed";
        var req2 = WebRequest.Create(url) as HttpWebRequest;
        req2.Method = "GET";
        InitializeRequest(req2);

        req2.Timeout = 300000;
        req2.Accept = MIME_TYPE;
        var response1 = (HttpWebResponse)req2.GetResponse();
        Stream responsestream2 = response1.GetResponseStream();
        WriteToFile("Second service called...");
        if (response1.StatusCode == HttpStatusCode.OK)
        {
            StreamReader responsereader1 = new StreamReader(responsestream2);
            jsonstring2 = responsereader1.ReadToEnd();
        }

        var output = JsonConvert.DeserializeObject<List<FailedDeviceList>>(jsonstring2);  // Will get List of the Failed devices
        List<int> deviceids = new List<int>();
        Reprocessdata reproc = new Reprocessdata();
        Reprocessdata.DeviceId rprod = new Reprocessdata.DeviceId();

        reproc.ForceFlag = true;
        reproc.ProductID = pid.Value;
        foreach (var dd in output)
        {
            rprod.ID = dd.DeviceId;
            reproc.DeviceIds.Add(rprod);
        }

        // Reprocess the Product in Devices
        var req3 = WebRequest.Create(ReprocessUrl) as HttpWebRequest;
        req3.Method = "POST";
        InitializeRequest(req3);
        req3.Accept = MIME_TYPE;
        req3.Timeout = 300000;
        req3.ContentType = "application/json";
        using (StreamWriter writer = new StreamWriter(req3.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(reproc);

            writer.Write(json);
            writer.Close();
        }
        System.Threading.Thread.Sleep(5000);
        var response5 = (HttpWebResponse)req3.GetResponse();
        WriteToFile("Third service called...");
        if (response5.StatusCode == HttpStatusCode.OK)
        {
            string result;
            using (StreamReader rdr = new StreamReader(response5.GetResponseStream()))
            {
                result = rdr.ReadToEnd();
            }
        }
    }
    response.Close();
}
catch (Exception ex)
{
    WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
}
}

上面代码中使用的方法

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    timer1 = new System.Timers.Timer();
    timer1.Interval = 60000; //every 1 min
    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
    timer1.Enabled = true;
    WriteToFile("Service has started..");
}

public void InitializeRequest(HttpWebRequest request)
{
    request.Headers.Add("aw-tenant-code", API_TENANT_CODE);
    request.Credentials = new NetworkCredential(USER_NAME, PASSWORD);
    request.KeepAlive = false;
    request.AddRange(1024);
}

当我联系服务人员时,他们说那里的一切都很好。这是我的代码有错误还是Windows服务不可靠?如何解决此问题?

When I contacted service provide they said everything fine from there side. Is this my code is buggy or windows service not reliable? How can I fix this issue?

注意:使用Visual Studio Code,Angular应用程序中的所有API都可以正常工作。这表示我的代码无法正常工作。

Note: All APIS are working fine from Angular application using Visual Studio Code. It means my code is not working.

Edit1::我正在使用的以下三个服务来自 VMware的文件

Three below services I am using from this document of VMware.

private const string HOST = "https:host/api/mdm/products/search?";
private const string FailedDevicesUrl = "https:host/api/mdm/products/";
private const string ReprocessUrl = "https:host/api/mdm/products/reprocessProduct";


推荐答案

响应http代码429表示您发送目标Web服务上的请求过多。

Response http code 429 indicates that you sending too many requests on target web service.

这意味着您尝试发送请求的服务具有一项策略,该策略会按时间限制阻止某些请求。

This means service you trying to send requests has a policies that blocks some requests by request-per-time limit.

我也承认,可以将外部服务手动配置为在您不知道的特定情况下抛出403代码。如果是这样,则可以在外部服务文档中说明此信息...:否

Also I admit that external service can be manually configured to throw 403 code in specific cases that you can't know about. If that, this information can be explained in external service documentation... or not :)

适应限制

您可以详细研究目标Web服务的限制,并设置代码以适应此限制。例如,如果服务受到限制,即每10分钟仅接收一个请求-您必须将计时器设置为每10分钟或更长时间发送一个请求。如果文档中没有提供此类信息-您可以通过查找一些带有外部服务响应的模式来进行手动测试。

Fit in limitations
You can make detailed research what limits target webservice has and set up your code to fit in this limitations. For example if service has limitation for receiving only one request per 10 minutes - you must set up your timer to send one request each 10 or more minutes. If documentation not provide such information - you can test it manually by finding some patterns with external service responses.

使用代理

每个限制策略基于有关请求发送者的信息。 通常该信息仅包含发送者的IP地址。这意味着,如果您从两个不同的IP地址发送2个请求-限制策略将认为就像2个不同的计算机发送这些请求一样。因此,您可以查找/购买/租用一些代理IP地址,然后在目标Web服务器上通过该地址发送请求。

Use proxy
Every limitation policy based on information about requests senders. Usually this information consists of IP address of sender only. This means if you send 2 requests from two different IP addresses - limitation policy will perceive that like 2 different computers sending these requests. So you can find/buy/rent some proxy IP addresses and send requests through there on target web server.

如何使用 WebRequest 您可以在答案中看到。

How to connect through proxy in C# using WebRequest you can see in this answer.

与外部服务提供商进行协商

如果您有可能与外部服务开发商或帮助中心进行交流,则可以要求他们减少IP地址的限制( (如果它是静态的)或提供一些机制来避免使用限制策略。如果由于某种原因他们不能提供此机会,至少您可以询问有关限制的详细信息。

Negotiate with external service provider
If you have possibility to communicate with external service developers or help center, you can ask their to reduce limitations for your IP address (if it static) or provide some mechanisms to avoid limitation policy for you. If for some reason they cannot provide this opportunity, at least you can ask detailed information about limitations.

重复机制

有时,您收到的外部错误 503 错误代码可能是由于服务不可用引起的。这意味着服务器可以处于维护状态或暂时超载。因此,您可以编写重复机制以向服务器连续发送请求,直到服务器可以访问为止。

Repetition mechanism
Some times 503 error code that is outer exception you received may be caused by service unavailable. It means that server can be under maintenance or temporary overloaded. So you can write repetition mechanism to make continious sending requests to server until it'll be accessible.

Polly 库可以帮助您创建重复机制

Polly library may help you with repetition mechanism creation

这篇关于HTTPS呼叫未连接到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆