【问题标题】:I got a System error in C# post我在 C# 帖子中遇到系统错误
【发布时间】:2023-03-12 14:35:01
【问题描述】:

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

平台: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);

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

【问题讨论】:

标签: c# post uwp


【解决方案1】:

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

根据您的要求,您可以制作一个方法来打包 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 可以参考。

【讨论】:

  • 谢谢!我会试试的。
  • 抛出什么异常?
  • 当我执行代码httpResponse = await client.PostAsync(requestUri, content);时,抛出异常:无法建立与服务器的连接。 res 是:{"status":-1,"msg":"Error! Invalid Request."}
  • 会不会是网页有问题?
  • 是的,你可以查看http状态码,如果码是200就说明你的请求成功了。
【解决方案2】:

我是服务器的作者。

现实是我还没有完成服务器的代码。

因此,{"status":-1,"msg":"Error! Invalid Request."} 是默认结果.....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-14
    • 2019-04-22
    • 2021-04-05
    • 2020-12-16
    • 2021-04-11
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多