Reputation:
I've set up a Jetty Server (written in Java) which handles HTTP requests. The server works fine, and when I use the Jetty HTTP client, I have no problems.
I'm now trying to send my server requests from C#. Here is my code -
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);
}
}
}
I can confirm from my server that it's receiving the request to the correct address, but inexplicably, the request content is null. It's never getting the content I'm trying to send over.
What might be going wrong?
Upvotes: 0
Views: 273
Reputation: 5018
Have you considered using WebClient
instead of HttpClient
? It takes care of much of the HTTP-creation code:
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);
}
}
}
}
Upvotes: 1