发送 HTTP 表单编码的请求 C#



我已经设置了一个处理HTTP请求的Jetty Server(用Java编写)。服务器工作正常,当我使用Jetty HTTP客户端时,我没有问题。

我现在正在尝试从 C# 发送服务器请求。这是我的代码 -

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class Requests
{
public static void Main ()
{
    RunAsync().Wait();
}
static async Task RunAsync ()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:8080/");
        var request = new HttpRequestMessage(HttpMethod.Post, "create");
        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("Topics001", "Batman"));
        postData.Add(new KeyValuePair<string, string>("Account", "5"));
        foreach (KeyValuePair<string,string> s in postData)
            Console.WriteLine(s);
        request.Content = new FormUrlEncodedContent(postData);
        var response = await client.SendAsync(request);
    }
}
}

我可以从我的服务器确认它正在接收到正确地址的请求,但令人费解的是,请求内容为空。它永远不会收到我试图发送的内容。

可能出现什么问题?

您是否考虑过使用 WebClient 而不是 HttpClient?它负责大部分HTTP创建代码:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Threading.Tasks;
namespace MyNamespace
{
    public class Requests
    {
        public static void Main()
        {
            RunAsync().Wait();
        }
        static async Task RunAsync()
        {
            using (var client = new WebClient())
            {
                var postData = new NameValueCollection()
                {
                    {"Topics001", "Batman"},
                    {"Account", "5"}
                };
                var uri = new Uri("http://localhost:8080/");
                var response = await client.UploadValuesTaskAsync(uri, postData);
                var result = System.Text.Encoding.UTF8.GetString(response);
            }
        }
    }
}

最新更新