2013-06-05 95 views
0

我正在使用HttpClient通過C#控制檯應用程序使用後發送數據到服務器。 HttpClient PostAsync無法發佈我試圖以各種格式發送的數據 即字符串內容,二進制內容,流內容,http內容通過Dictionary對象但post是空的,服務器返回請求無效的異常下面是我的代碼無法通過HttpClient發佈數據PostAsync

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Net.Http; 
using System.Windows; 
using System.Windows.Input; 
using System.IO; 
using System.Web; 


namespace ConsoleApplication1 
{ 
    class Program 
    { 
     string str = ""; int j = 0; 
     static void Main(string[] args) 
     { 
      Program df = new Program(); 

      df.Started(); 

     } 


     public async void Started() 
     { 
      string contentLength="0"; 
      try 
      { 
       contentLength = await AccessTheWebAsync(); 
      } 
      catch (Exception e) 
      { 

      } 


      Console.WriteLine(contentLength); 
     } 

     async Task<string> AccessTheWebAsync() 
     { 
      HttpClient client = new HttpClient(); 

      string token = "qwerty1234"; 
      string test = "1"; 
      string postrequest = "<?xml version='1.0' encoding='UTF-8'?>" + 
           "<request> " + 
           "<rec>asdf1234</rec> " + 
           " <lid>9876</lid> " + 
           "</request> "; 


      Dictionary<string, string> dict = new Dictionary<string, string>(); 
      dict.Add("token", token); 
      dict.Add("test", test); 
      dict.Add("request", postrequest); 

      HttpContent content = new FormUrlEncodedContent(dict); 

      Uri url = new Uri("http://example.com/"); 

      Task<HttpResponseMessage> getStringTask = client.PostAsync(url, content);  

      HttpResponseMessage httpmesssage = await getStringTask; 
      Stream respons = await httpmesssage.Content.ReadAsStreamAsync(); 
      StreamReader sr = new StreamReader(respons); 
      string response = sr.ReadToEnd(); 
      return response; 

     } 



     } 

} 

在此先感謝

+3

你看發生了什麼事時,透過Wireshark的提琴手或HTTP級別? –

回答

0

在控制檯應用程序,你需要等待操作完成,或者使用Task.WaitConsole.ReadKey,或類似的。此外,避免async void

static void Main(string[] args) 
{ 
    Program df = new Program(); 
    df.StartedAsync().Wait(); 
} 

public async Task StartedAsync() 
+0

我試過這個,但是這對我不起作用我得到了同樣的無效請求異常 –

+0

請編輯你的問題,包括堆棧跟蹤在內的異常細節。 –