How to convert curl request to HttpClient

Sonja picture Sonja · Apr 12, 2017 · Viewed 7.2k times · Source

I have a curl request that looks like this:

curl -i -XPOST 'http://my_url:port/write?db=myDb' -u user:xxxxx --data-binary 'FieldName,host=M.233 value=52.666 timestamp'

I'm trying to post this request using HttpClient. I'm not sure how exactly I should call it. This is what I tried to do:

public async void  TestHttpClient()
{ 
    var client = new HttpClient();
    var credentials = Encoding.ASCII.GetBytes("user:xxxxx");
    var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
    client.DefaultRequestHeaders.Authorization = header;
    client.BaseAddress = new Uri("http://my_url:port/write?db=myDb");
    var result = await client.PostAsync(..);
}

Which parameters should I write for PostAsync()?

How to convert --data-binary and FieldName,host=M.233 value=52.666 timestamp from curl to HttpClient?

Answer

Sonja picture Sonja · Sep 29, 2017

The solution for me was:

public async Task TestHttpClient()
{ 
    var client = new HttpClient();
    var credentials = Encoding.ASCII.GetBytes("user:xxxxx");
    var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));
    client.DefaultRequestHeaders.Authorization = header;
    String url = "http://my_url:port/write?db=myDb";
    String content = "FieldName,host=M.233 value=52.666 timestamp";
    StringContent stringContent = new StringContent(content);
    var result = await client.PostAsync(url, stringContent);
}