如何为StreamWriter设置TimeOut?

时间:2018-02-04 08:20:09

标签: c# post streamreader

我正在使用此代码从Server接收数据。但我不知道如何为它设置超时。我从PostInput Model收到一个字符串:ContentType,Json,WebRequest。

这是我的代码:

public string PostMethod(PostInput Input)
{
    try
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(Input.WebRequest);
        httpWebRequest.ContentType = Input.ContentType;
        httpWebRequest.Method = "POST";                

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {                                        
            streamWriter.Write(Input.Json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        string result;
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }
        return result;

    }
    catch (Exception ex)
    {
        return string.Empty;
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用HttpWebRequest类的Timeout属性。

简单的代码如:

httpWebRequest.ContentType = Input.ContentType;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout= 10000; // 10 seconds

HttpWebRequest.Timeout

答案 1 :(得分:1)

朋友

我找到了新方法, 我ping ip,如果可用则调用StreamWriter

这是我的研究结果:

public string PostMethod(PostInput Input)
    {

        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(Input.WebRequest);
            httpWebRequest.ContentType = Input.ContentType;
            httpWebRequest.Method = "POST";

            PingReply Objping = new Ping().Send(IPAddress.Parse(Input.Address), 1000);

            string result;

            if (Objping.Status == IPStatus.Success)
            {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(Input.Json);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
                return result;
            }

            return null;   
        }

答案 2 :(得分:1)

您可以尝试使用WebClinet,如此

 using (WebClient client = new WebClient())
            {
                using (Stream stream = client.OpenWrite(Input.WebRequest.RequestUri))
                using (StreamWriter reader = new StreamWriter(stream))
                {
                    stream.WriteTimeout = 200;

                }
            }