我已经设置了一个处理HTTP请求的Jetty服务器(用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);
}
}
}
我可以从我的服务器确认它正在接收到正确地址的请求,但莫名其妙地,请求内容为空。它永远不会得到我试图发送的内容。
可能出现什么问题?
答案 0 :(得分:1)
您是否考虑过使用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);
}
}
}
}