HttpClient PostAsync System.Net.Http.HttpRequestException: 发送请求时出错
HttpClient PostAsync System.Net.Http.HttpRequestException: An error occurred while sending the request
我正在开发一个使用网络服务 (http) 的简单控制台程序。
将 post json 字符串来自 txt 文件。
我自己测试了下面的代码段 api 工作正常。
使用 post 人工 post 向 api 发出请求并得到回复。
static void Main(string[] args)
{
//System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
HttpClient client = new HttpClient(); //should be instatiated once per application
do
{
try
{
Console.WriteLine("Enter Method:");
string Method = Console.ReadLine();
Console.WriteLine("Enter URI:");
string uri = Console.ReadLine();
if (("POST,PUT").Split(',').Contains(Method.ToUpper()))
{
Console.WriteLine("Enter FilePath:");
string FilePath = Console.ReadLine();
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "File Path : <", FilePath + ">"));
string str_content = (File.OpenText(@FilePath)).ReadToEnd();
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "String data : <", str_content + ">"));
//StringContent class creates a formatted text appropriate for the http server/client communication
StringContent httpContent = new StringContent(str_content, System.Text.Encoding.UTF8, "application/json");
iLog.Log(iLog.EVENT, string.Format("1")); //trace
try
{
//Some risky client call that will call parallell code / async /TPL or in some way cause an AggregateException
var postTask = client.PostAsync(uri, httpContent);
iLog.Log(iLog.EVENT, string.Format("2")); //trace
postTask.Wait();
iLog.Log(iLog.EVENT, string.Format("3")); //trace
//gets the response back from the API service
HttpResponseMessage result = postTask.Result;
iLog.Log(iLog.EVENT, string.Format("4")); //trace
if (result.IsSuccessStatusCode)
{
iLog.Log(iLog.EVENT, string.Format("5")); //trace
//use this if you want a raw json string
var readTask = result.Content.ReadAsStringAsync();
iLog.Log(iLog.EVENT, string.Format("6")); //trace
readTask.Wait();
iLog.Log(iLog.EVENT, string.Format("7")); //trace
var str_Response = readTask.Result.ToString();
iLog.Log(iLog.EVENT, string.Format("8")); //trace
Console.WriteLine("WebService Response : \n<" + str_Response + ">");
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "WebService Response : <", str_Response + ">"));
}
else
{
Console.WriteLine("Status Code = " + result.StatusCode);
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "StatusCode", result.StatusCode));
iLog.Log(iLog.EVENT, string.Format("9")); //trace
}
}
catch (AggregateException err)
{
foreach (var errInner in err.InnerExceptions)
{
iLog.Log(iLog.ERROR, string.Format(errInner.ToString())); //trace
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
iLog.Log(iLog.EVENT, string.Format("{0} | {1}", "Exception", ex.Message.ToString()));
iLog.Log(iLog.EVENT, string.Format("10")); //trace
}
iLog.Log(iLog.EVENT, string.Format("{0} {1}", "END", "----------------------------" + "\n"));
Console.WriteLine("Do you want to continue?");
} while (Console.ReadLine().ToUpper() == "Y");
}
返回错误:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
嗨,通过使用 Caius Jard 的建议,即使用添加 restsharp nuget 并替换为 Postman 生成的代码,您可以让它工作。
我正在开发一个使用网络服务 (http) 的简单控制台程序。 将 post json 字符串来自 txt 文件。
我自己测试了下面的代码段 api 工作正常。
使用 post 人工 post 向 api 发出请求并得到回复。
static void Main(string[] args)
{
//System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
HttpClient client = new HttpClient(); //should be instatiated once per application
do
{
try
{
Console.WriteLine("Enter Method:");
string Method = Console.ReadLine();
Console.WriteLine("Enter URI:");
string uri = Console.ReadLine();
if (("POST,PUT").Split(',').Contains(Method.ToUpper()))
{
Console.WriteLine("Enter FilePath:");
string FilePath = Console.ReadLine();
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "File Path : <", FilePath + ">"));
string str_content = (File.OpenText(@FilePath)).ReadToEnd();
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "String data : <", str_content + ">"));
//StringContent class creates a formatted text appropriate for the http server/client communication
StringContent httpContent = new StringContent(str_content, System.Text.Encoding.UTF8, "application/json");
iLog.Log(iLog.EVENT, string.Format("1")); //trace
try
{
//Some risky client call that will call parallell code / async /TPL or in some way cause an AggregateException
var postTask = client.PostAsync(uri, httpContent);
iLog.Log(iLog.EVENT, string.Format("2")); //trace
postTask.Wait();
iLog.Log(iLog.EVENT, string.Format("3")); //trace
//gets the response back from the API service
HttpResponseMessage result = postTask.Result;
iLog.Log(iLog.EVENT, string.Format("4")); //trace
if (result.IsSuccessStatusCode)
{
iLog.Log(iLog.EVENT, string.Format("5")); //trace
//use this if you want a raw json string
var readTask = result.Content.ReadAsStringAsync();
iLog.Log(iLog.EVENT, string.Format("6")); //trace
readTask.Wait();
iLog.Log(iLog.EVENT, string.Format("7")); //trace
var str_Response = readTask.Result.ToString();
iLog.Log(iLog.EVENT, string.Format("8")); //trace
Console.WriteLine("WebService Response : \n<" + str_Response + ">");
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "WebService Response : <", str_Response + ">"));
}
else
{
Console.WriteLine("Status Code = " + result.StatusCode);
iLog.Log(iLog.EVENT, string.Format(" {0} | {1}", "StatusCode", result.StatusCode));
iLog.Log(iLog.EVENT, string.Format("9")); //trace
}
}
catch (AggregateException err)
{
foreach (var errInner in err.InnerExceptions)
{
iLog.Log(iLog.ERROR, string.Format(errInner.ToString())); //trace
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
iLog.Log(iLog.EVENT, string.Format("{0} | {1}", "Exception", ex.Message.ToString()));
iLog.Log(iLog.EVENT, string.Format("10")); //trace
}
iLog.Log(iLog.EVENT, string.Format("{0} {1}", "END", "----------------------------" + "\n"));
Console.WriteLine("Do you want to continue?");
} while (Console.ReadLine().ToUpper() == "Y");
}
返回错误:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly. at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- End of inner exception stack trace ---
嗨,通过使用 Caius Jard 的建议,即使用添加 restsharp nuget 并替换为 Postman 生成的代码,您可以让它工作。