Skip to content

Instantly share code, notes, and snippets.

@if1live
Created January 15, 2019 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save if1live/7e5abed2e75f8ceec7e343770d4f4f01 to your computer and use it in GitHub Desktop.
Save if1live/7e5abed2e75f8ceec7e343770d4f4f01 to your computer and use it in GitHub Desktop.
c# HttpClient + GET + json body
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace httpclient
{
[DataContract]
internal class SimpleReq
{
[DataMember]
public string foo;
}
class Program
{
private static readonly HttpClient client = new HttpClient();
public static byte[] ToJsonBinary<T>(T data)
{
var stream1 = new MemoryStream();
var ser = new DataContractJsonSerializer(typeof(T));
ser.WriteObject(stream1, data);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
var jsonBody = sr.ReadToEnd();
byte[] byteArray = Encoding.UTF8.GetBytes(jsonBody);
return byteArray;
}
public static string ToJsonString<T>(T data)
{
var stream1 = new MemoryStream();
var ser = new DataContractJsonSerializer(typeof(T));
ser.WriteObject(stream1, data);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
var jsonBody = sr.ReadToEnd();
return jsonBody;
}
async Task<bool> RequestResource()
{
var host = "http://127.0.0.1:3100";
var path = "/v1/user/mydata";
var body = ToJsonString(new SimpleReq()
{
foo = "bar",
});
var request = new HttpRequestMessage(HttpMethod.Get, $"{host}{path}")
{
Headers = {
{ HttpRequestHeader.ContentType.ToString(), "application/json"},
},
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
Console.WriteLine(request.Headers);
var resp = await client.SendAsync(request);
Console.WriteLine(resp.StatusCode);
Console.WriteLine(await resp.Content.ReadAsStringAsync());
return true;
}
static void Main(string[] args)
{
var x = new Program();
var task = x.RequestResource();
task.Wait();
Console.WriteLine("Hello World!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment