allocator
allocator

Reputation: 91

C# HttpClient POST request

i'm trying to create a POST request and I can't get it to work.

this is the format of the request which has 3 params, accountidentifier / type / seriesid

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

and this is my 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);
}

Any ideas?

Upvotes: 4

Views: 27623

Answers (2)

TurboWindex
TurboWindex

Reputation: 76

IMO, dictionaries in C# are very useful for this kind of task. Here is an example of an async method to complete a wonderful POST request:

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();
    }
}

Upvotes: 4

FlavorScape
FlavorScape

Reputation: 14269

You can try WebClient too. It tries to accurately simulate what a browser would do:

            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);

Where UploadValuesAsync POSTs your collection.

Upvotes: -2

Related Questions