这是我第一次在这里提问(我来自亚洲)。
Platform:UWP 17632
IDE : Visual Studio 2017
根据项目的需求,我需要将一些信息发布到网站上。
我引用关于How to make HTTP POST web request的答案方法A。
这是我的代码:
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);
我想知道为什么并获得可以解决它的解决方案。
如果您能帮助我,我将不胜感激。
最佳答案
建议使用 HttpClient
和 Windows.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 sample和 document你可以引用一下。
关于c# - 我在 C# 帖子中遇到系统错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51113944/