簡體   English   中英

我在C#帖子中遇到系統錯誤

[英]I got a System error in C# post

這是我第一次在這里問一個問題(我來自亞洲)。

平台:UWP 17632

IDE:Visual Studio 2017

基於項目的重新設計,我需要將一些信息發布到網站上。

我參考有關如何使HTTP POST Web請求方法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);

我想知道為什么並獲得可以解決它的解決方案。
如果您能幫助我,我將不勝感激。

建議使用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;

});

並且有官方代碼示例文檔供您參考。

我是服務器的作者。

現實是我還沒有完成服務器的代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM