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

标签 c# post uwp

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

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/

相关文章:

c# - 移动要托管的 XML 文件

c# - 使用 C# 删除 SharePoint 文件夹中的文件

c# - ASP.NET MVC - 下拉列表后处理问题

java - 没有主题备用 DNS 名称匹配

c# - 如何从不同来源同步播放视频和音频?

c# - Azure 服务总线不断抛出 MessageLockLostException

c# - 错误 Paypal 沙箱 : The request was aborted: Could not create SSL/TLS secure channel

JavaScript:发送 POST,重定向到响应

c# - 使特定的 ListView 项目在通用 Windows 平台中不可点击

c# - 无法使用 UWP 在工具栏项目中显示按钮图标