4

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
allocator
  • 91
  • 1
  • 1
  • 9
  • Can you debug and see what the full uri is of httpClient when the post is called? – Cubicle.Jockey Jul 24 '13 at 22:40
  • 1
    The parameters you mentioned are part of the `URI` (the query part, after the `?`), but you send them as `content`. – user1908061 Jul 24 '13 at 22:41
  • @Cubicle.Jockey can't really find it. – allocator Jul 24 '13 at 22:43
  • @user1908061 damn, can you give me a reference to use or something? – allocator Jul 24 '13 at 22:44
  • @allocator Uhm, the wikipedia article of HTTP? There is not really much to say. You request the URI `/api/User_Favorites.php`, but the query part (`?accountid=...`) is also part of the URI you want to request and you omit it. And the other hand you apparently don't even know what this API expects as content to be sent. You should figure this out first, and this is something we can't possibly know. – user1908061 Jul 24 '13 at 22:47
  • @user1908061 I've fixed the code but PostAsync method also has a content parameter, There I just sent an empty content ? – allocator Jul 24 '13 at 22:53
  • @allocator Please let me quote myself from my earlier comment: `you apparently don't even know what this API expects as content to be sent. You should figure this out first, and this is something we can't possibly know.` – user1908061 Jul 24 '13 at 22:54
  • Check this answer for help: http://stackoverflow.com/questions/15176538/net-httpclient-how-to-post-string-value – nelsonmichael Jul 24 '13 at 23:10
  • @nelsonmichael already checked that thread but thank you. – allocator Jul 24 '13 at 23:14

2 Answers2

4

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();
    }
}
  • Using .NET 6 and can't find FormUrlEncodedContent anywhere. According to the docs it should be in System.Net.Http but it's not for me. I installed the nuget package named after the namespace and its description even mentions the class but it's still not there. – TheBoxyBear Nov 05 '21 at 02:05
  • So turns out it's an IntelliSense bug that happens with a lot of people. I pasted the class name after new and it did detect it, it just wasn't sussgesting the name for some reason. – TheBoxyBear Nov 05 '21 at 02:10
-2

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.

FlavorScape
  • 13,301
  • 12
  • 75
  • 117
  • 3
    HttpClient is basically the new enhanced version of WebClient, developed for the growing need of calling REST apis. – user1908061 Jul 24 '13 at 23:09
  • @user1908061 you should try to help more and flame less. – allocator Jul 24 '13 at 23:16
  • @allocator I'm no´t flaming. Here I just mentioned that the newer HttpClient class was designed for cases like yours. In your question you have problems calling an API, but you don't tell us which. You don't know how to proper call it yourself.. So how are we supposed to help? I pointed out the only visible mistake from your question. – user1908061 Jul 24 '13 at 23:39
  • @user1908061 I changed my code to this http://pastebin.com/3GUUBUcV but still I can't get it to work or decide what content shoud be sent. this is the API page reference http://thetvdb.com/wiki/index.php/API:User_Favorites – allocator Jul 25 '13 at 05:36
  • @allocator Unfortunately that documentation is very poorly written. It does not mention which HTTP verb you should use.. I would try to use `GetAsync` instead of `PostAsync` and see what you get. – user1908061 Jul 25 '13 at 08:33
  • @user1908061 yeap, that's what I did, I used GetAsync and it worked like a charm :D – allocator Jul 25 '13 at 21:10