gpt4 book ai didi

c# - 我在 C# 帖子中遇到系统错误

转载 作者:行者123 更新时间:2023-11-30 20:25:42 24 4
gpt4 key购买 nike

这是我第一次在这里提问(我来自亚洲)。

Platform:UWP 17632

IDE : Visual Studio 2017

根据项目需求,我需要发布一些信息到一个网站。

我引用了关于 How to make HTTP POST web request 的答案方法A。

enter image description here

这是我的代码:

public async void PostDataAsync(string pTemperture, string pHumidity, string pFireStatus, string pLightStatus, string pBodyStatus)
{
var values = new Dictionary<string, string>
{
{"count", "1" },
{"temperture_0", pTemperture },
{"Humidity_0", pHumidity },
{"FireStatus_0", pFireStatus },
{"LightStatus_0" ,pLightStatus},
{"BodyDetect_0", pBodyStatus }
};
var content = new FormUrlEncodedContent(values);
try
{
var response = await client.PostAsync("http://115.159.36.210/api/onehome/upload", content);//Here throw an exception
System.Diagnostics.Debug.WriteLine(response);
var responseString = response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(responseString);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.HelpLink);
System.Diagnostics.Debug.WriteLine(ex.Message);
throw;
}
}

然后抛出异常

“An error occurred while sending the request.” 

var response = await client.PostAsync("http://115.159.36.210/api/onehome/upload", content);

我想知道为什么并获得可以解决它的解决方案。
如果你能帮助我,我将不胜感激。

最佳答案

建议使用 HttpClientWindows.Web.Http 的其余部分命名空间 API,用于在 UWP 中使用 HTTP 2.0 和 HTTP 1.1 协议(protocol)发送和接收信息。

根据您的要求,您可以创建一个方法来打包 http POST 方法,如下所示

public async void SendPostMethod(string url, Dictionary<string, string> param, Action<string> response)
{
HttpClient client = new HttpClient();

HttpResponseMessage httpResponse = new HttpResponseMessage();
Uri requestUri = new Uri(url);

var content = new HttpFormUrlEncodedContent(param);
try
{
httpResponse = await client.PostAsync(requestUri, content);

response(await httpResponse.Content.ReadAsStringAsync());
}
catch (Exception ex)
{

}

}

用法

 this.SendPostMethod("http://115.159.36.210/api/onehome/upload",Param, (res) =>
{

var response = res;

});

还有官方code sampledocument你可以引用。

关于c# - 我在 C# 帖子中遇到系统错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51113944/

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