2013-09-24 40 views
148
public static async Task<string> GetData(string url, string data) 
{ 
    UriBuilder fullUri = new UriBuilder(url); 

    if (!string.IsNullOrEmpty(data)) 
     fullUri.Query = data; 

    HttpClient client = new HttpClient(); 

    HttpResponseMessage response = await client.PostAsync(new Uri(url), /*expects HttpContent*/); 

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 
    response.EnsureSuccessStatusCode(); 
    string responseBody = await response.Content.ReadAsStringAsync(); 

    return responseBody; 
} 

PostAsync需要另一個參數,需要是HttpContent如何爲我的HttpClient PostAsync第二個參數設置HttpContent?

如何設置HttpContent?沒有任何文檔適用於Windows Phone 8.

如果我的電子郵件地址是GetAsync,它的效果非常好!但它需要用POST鍵=「喇嘛」的內容,一些=「耶」

//編輯

感謝這麼多的答案......這工作得很好,但仍然是一個這裏很少unsures:

public static async Task<string> GetData(string url, string data) 
    { 
     data = "test=something"; 

     HttpClient client = new HttpClient(); 
     StringContent queryString = new StringContent(data); 

     HttpResponseMessage response = await client.PostAsync(new Uri(url), queryString); 

     //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 
     response.EnsureSuccessStatusCode(); 
     string responseBody = await response.Content.ReadAsStringAsync(); 

     return responseBody; 
    } 

的數據「測試=東西」我以爲會拿起的API一側後數據「測試」,顯然事實並非如此。另一方面,我可能需要通過發佈數據發佈整個對象/數組,所以我認爲json最好這樣做。有關我如何獲取發佈數據的任何想法?

也許是這樣的:

class SomeSubData 
{ 
    public string line1 { get; set; } 
    public string line2 { get; set; } 
} 

class PostData 
{ 
    public string test { get; set; } 
    public SomeSubData lines { get; set; } 
} 

PostData data = new PostData { 
    test = "something", 
    lines = new SomeSubData { 
     line1 = "a line", 
     line2 = "a second line" 
    } 
} 
StringContent queryString = new StringContent(data); // But obviously that won't work 

回答

89

這在一些問題的答案回答到Can't find how to use HttpContent以及在此blog post

總之,您不能直接設置HttpContent的實例,因爲它是一個抽象類。您需要根據您的需要使用從其派生的類。最有可能的是StringContent,它允許您在構造函數中設置響應的字符串值,編碼和媒體類型。請參閱:http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

+2

我會檢查一下。我想當我發現這一點時,我將不得不把這個地方放在每個人都可以看到的地方!這讓我有4天的時間,試圖獲得一個簡單的REST到API。 – Jimmyt1988

+0

該StringContent工作得很好,但實際上,不能讓PostData通過我現在打電話的網站:D。 – Jimmyt1988

+2

回答「我如何發佈我的類的JSON代理」是「將對象序列化爲JSON,可能是使用JSON.Net」,但這確實屬於一個單獨的問題。 –

29

要添加到普雷斯頓的答案,這裏的HttpContent派生類的標準庫提供的完整列表:

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

信用https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

還有一個所謂的ObjectContent但我無法在ASP.NET Core中找到它。

當然,你可以用Microsoft.AspNet.WebApi.Client擴展跳過整個HttpContent事情都在一起(你必須做一個進口讓它在ASP.NET核心工作現在:https://github.com/aspnet/Home/issues/1558),然後你可以做的事情一樣:

​​
相關問題