首页 新闻 会员 周边

使用HttpClient 请求,一段时间后出现下面错误

0
悬赏园豆:5 [已解决问题] 解决于 2023-06-21 09:27

public static HttpResponseMessage HttpPost2(string url, string body = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30)
{
body = body ?? "";
SetCertificatePolicy();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(body, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
                return response;
                //return response.Content.ReadAsStringAsync().Result;
            }
        }
    }

HttpClient 内部异常堆栈跟踪的结尾
2023-06-12 17:20:31,933 [79] ERROR MessageSendService.Services.SendSmsServices [(null)] - System.AggregateException: 发生一个或多个错误。 ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: 无法连接到远程服务器 ---> System.Net.Sockets.SocketException: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
在 System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)
在 System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
在 System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- 内部异常堆栈跟踪的结尾 ---
在 System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
在 System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- 内部异常堆栈跟踪的结尾 ---
--- 内部异常堆栈跟踪的结尾 ---
在 System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) 在 System.Threading.Tasks.Task1.get_Result()
在 CTWFramework.Services.Implementation.HttpClinetService.HttpPost2(String url, String body, String contentType, Dictionary`2 headers, Int32 timeOut) 位置 d:\ctw-SourceCode\MessageClient\MessageClient\CTWFramework.Services\Implementation\HttpClinetService.cs:行号 79
在 MessageSendService.Services.SendSmsServices.<>c__DisplayClass6.<PostMessage2>b__5() 位置 d:\ctw-SourceCode\MessageClient\MessageClient\MessageSendService\Services\SendSmsServices.cs:行号 186
---> (内部异常 #0) System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: 无法连接到远程服务器 ---> System.Net.Sockets.SocketException: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
在 System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)
在 System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
在 System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- 内部异常堆栈跟踪的结尾 ---
在 System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
在 System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- 内部异常堆栈跟踪的结尾 ---<---

剧里局外的主页 剧里局外 | 初学一级 | 园豆:3
提问于:2023-06-13 10:15
< >
分享
最佳答案
0

可以换一种写法连接同一个服务器试试,看看是代码的问题还是服务器或网络的问题:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                client.DefaultRequestHeaders.Add("User-Agent", "MyHttpClient");

                var data = new { name = "John", age = 30 };
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync("https://www.example.com/api/users", content);

                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code {response.StatusCode}");
                }
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"Request failed: {ex.Message}");
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine("Request timed out");
        }
    }
}
收获园豆:3
lanedm | 老鸟四级 |园豆:2381 | 2023-06-13 10:42
其他回答(1)
0

这个错误提示表明在发送请求时出现了连接问题,可能是由于网络连接中断或远程服务器无响应导致的。下面是一些可能的解决方案:

网络连接问题:确保你的计算机和远程服务器之间的网络连接正常。尝试访问其他网站或服务,确认网络连接没有问题。

远程服务器问题:确认远程服务器是否正常运行并且可访问。你可以尝试通过浏览器或其他工具访问相同的URL,看是否能够成功连接和获取响应。

超时设置:尝试增加超时时间,以避免请求过早超时。你可以尝试将timeOut参数增加到更长的时间,例如60秒。

重试机制:考虑添加一个重试机制,以处理临时的连接问题。在遇到连接错误时,可以尝试重新发送请求一定次数,以增加请求成功的机会。

安全防火墙和代理:如果你的计算机处于受限制的网络环境中,例如通过防火墙或代理访问互联网,确保相关的安全设置已正确配置,以允许应用程序进行网络通信。

调试和日志记录:尝试添加更详细的调试信息和日志记录来帮助排查问题。你可以输出更多的错误信息、异常堆栈跟踪和请求/响应的详细信息,以便更好地了解问题所在。

如果尝试了以上方法仍然无法解决问题,可能需要进一步排查。你可以尝试搜索与HttpClient和远程服务器连接问题相关的文档、教程或社区帖子,或向HttpClient或相关组件的支持渠道寻求帮助。

收获园豆:2
Technologyforgood | 园豆:5698 (大侠五级) | 2023-06-13 22:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册