gpt4 book ai didi

C# Restful 客户端 - 连接超时

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:17 25 4
gpt4 key购买 nike

我正在使用 WinForms 并访问我的 Restful 网络服务。由于某种原因,代码在连接到服务器时出现超时错误后会中断。

问题也可能是由于我的代码设计。这是我的 Restful 客户端类

public class Restful
{
public string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("MyUserName:MyPassword"));

public string POST(string parameters)
{
var request = (HttpWebRequest)WebRequest.Create("http://myserverdomain.com/api/webservice/someMethod");

byte[] byteArray = Encoding.UTF8.GetBytes(parameters);

request.Method = WebRequestMethods.Http.Post;
request.Headers["Authorization"] = this.auth;
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";

Stream postStream = null;

try
{
// ERROR IS IN THIS LINE
postStream = request.GetRequestStream();
}
catch (WebException ex)
{
// I'm kind of creating an hack here..which isn't good..
if (ex.Status.ToString() == "ConnectFailure")
{
System.Threading.Thread.Sleep(1000);
this.POST(parameters);
}
}

if (postStream == null)
return string.Empty;

postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();

using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;

if (response.StatusCode != HttpStatusCode.OK)
return responseValue;

using (var responseStream = response.GetResponseStream())
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
responseValue = reader.ReadToEnd();

return responseValue;
}
}
}

我收到错误消息(在几次成功发送项目后):

Unable to connect to remote server

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond MyServerIpAddress

有时我向服务器发送数千个项目,有时我只发送 2 或 4 个。所以我在一个循环中调用这个 POST 函数

try
{
foreach (app.views.Documents doc in DocumentsView)
{
var parameters = "key=" + doc.key;
parameters += "&param1=" + doc.param1 + "&param2=" + doc.param2;

/*
* Validates the response of Restful service.
* The response is always in JSON format.
*/
if (response(Restful.POST(parameters)) == false)
{
MessageBox.Show("Error while sending the ID: " + doc.id.ToString());
break;
};
}
}
catch (Exception ex)
{
MessageBox.Show("Error while sending documents: " + ex.Message);
}

最佳答案

您可以将 HttpWebRequest 的默认超时更改为比默认值更大的值,例如:

request.Timeout = 120000;

我认为默认值是 100 秒。

你也可以查看这个adjusting-httpwebrequest-connection-timeout-in-c-sharp

关于C# Restful 客户端 - 连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35992025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com