簡體   English   中英

C#HttpClient POST請求

[英]C# HttpClient POST request

我正在嘗試創建POST請求,但無法正常工作。

這是具有3個參數的請求的格式,即accountidentifier / type / seriesid

http://someSite.com/api/User_Favorites.php?accountid=accountidentifier&type=type&seriesid=seriesid

這是我的C#

using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri("http://somesite.com");
            var content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("accountidentifier", accountID),
                new KeyValuePair<string, string>("type", "add"),
                new KeyValuePair<string, string>("seriesid", seriesId),

            });

            httpClient.PostAsync("/api/User_Favorites.php", content);
}

有任何想法嗎?

IMO,C#中的詞典對於此類任務非常有用。 這是一個異步方法的示例,可以完成一個美妙的POST請求:

public class YourFavoriteClassOfAllTime {

    //HttpClient should be instancied once and not be disposed 
    private static readonly HttpClient client = new HttpClient();

    public async void Post()
    {

        var values = new Dictionary<string, string>
        {  
            { "accountidentifier", "Data you want to send at account field" },
            { "type", "Data you want to send at type field"},
            { "seriesid", "The data you went to send at seriesid field"
            }
        };

        //form "postable object" if that makes any sense
        var content = new FormUrlEncodedContent(values);

        //POST the object to the specified URI 
        var response = await client.PostAsync("http://127.0.0.1/api/User_Favorites.php", content);

        //Read back the answer from server
        var responseString = await response.Content.ReadAsStringAsync();
    }
}

您也可以嘗試使用WebClient。 它試圖准確模擬瀏覽器將執行的操作:

            var uri = new Uri("http://whatever/");
            WebClient client = new WebClient();
            var collection = new Dictionary<string, string>();
            collection.Add("accountID", accountID );
            collection.Add("someKey", "someValue");
            var s = client.UploadValuesAsync(uri, collection);

UploadValuesAsync在哪里發布您的集合。

暫無
暫無

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

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