C# HttpClient POST 请求

4

我正在尝试创建一个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);
}

有什么想法吗?

你能调试一下并查看在调用post方法时httpClient的完整uri是什么吗? - Cubicle.Jockey
1
你提到的参数是URI的一部分(即在?之后的查询部分),但你将它们作为content发送。 - user1908061
@Cubicle.Jockey 确实找不到它。 - allocator
@user1908061,能否给我一个参考或者什么东西吗? - allocator
请查看以下答案以获取帮助:https://dev59.com/f2Up5IYBdhLWcg3wmIUs - nelsonmichael
显示剩余4条评论
2个回答

4

在我看来,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();
    }
}

使用.NET 6,但无法找到FormUrlEncodedContent。根据文档,它应该在System.Net.Http中,但对我来说并不是这样。我安装了以命名空间命名的nuget包,其描述甚至提到了该类,但它仍然不存在。 - TheBoxyBear
原来这是一个IntelliSense的bug,很多人都遇到过。我在new后面粘贴了类名,它确实检测到了,只是由于某种原因没有建议名称。 - TheBoxyBear

-2

你也可以尝试使用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会将你的集合以POST方式提交。


3
HttpClient基本上是WebClient的新增强版本,为了满足调用REST API不断增长的需求而开发。 - user1908061
@user1908061,你应该尽量多帮助别人,少一些挑衅。 - allocator
@allocator 我并没有恶意攻击。我只是提到新的HttpClient类是为像你这样的情况而设计的。在你的问题中,你遇到了调用API的问题,但你没有告诉我们具体是哪个API。你自己也不知道如何正确地调用它。那么我们应该如何帮助你呢?我只是指出了你问题中唯一可见的错误。 - user1908061
@user1908061 我把代码改成了这个 http://pastebin.com/3GUUBUcV但是我仍然无法让它工作或决定应该发送哪些内容。这是API页面的参考 http://thetvdb.com/wiki/index.php/API:User_Favorites - allocator
@allocator 很遗憾,那份文档写得非常糟糕。它没有提到应该使用哪个HTTP动词...我建议尝试使用GetAsync而不是PostAsync,看看会发生什么。 - user1908061
@user1908061 是的,那就是我所做的,我使用了GetAsync,它非常好用 :D - allocator

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接