Code 1 HttpWebRequest works fine
public static void Send1()
{
var req = WebRequest.CreateHttp(MalHost + ":" + MalPort.ToString() +
"/api/v1/subscriptions/new");
req.ContentType = "application/json";
req.Method = "POST";
req.Accept = "*/*";
var jsonBody = new SubscriptionJson();
jsonBody.CallBack.Address = ReceiverHost + ":" + MalPort.ToString();
jsonBody.CallBack.Method = "POST";
jsonBody.Type = "recognition";
var filter = new FilterProperty
{
Channels = new int[] { 0},
DecisionComposition = new string[] { "Plate", "Channel" },
ImagesComposition = new string[] { },
};
jsonBody.Filter = JsonConvert.SerializeObject(filter);
string serObj = JsonConvert.SerializeObject(jsonBody);
Debug.Print(serObj);
var body = Encoding.UTF8.GetBytes(serObj);
req.ContentLength = body.Length;
using (var sw = req.GetRequestStream())
{
sw.Write(body, 0, body.Length);
}
using (var resp = (HttpWebResponse)req.GetResponse())
using (var respStream = resp.GetResponseStream())
using (var sr = new StreamReader(respStream))
{
Debug.Print(resp.StatusCode.ToString());
//Debug.Print(sr.ReadToEnd());
string ResJson = sr.ReadToEnd();
Subscription sub = JsonConvert.DeserializeObject<Subscription>(ResJson);
CurrentSubscription = sub.id;
Debug.Print(CurrentSubscription);
}
}
Code 2 HttpClient. Responce return the 406 error (Not Accceptable).
public static async Task<bool> Send2()
{
HttpClient httpClient = new HttpClient();
string endpoint = MalHost + ":" + MalPort.ToString() + "/api/v1/subscriptions/new";
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
HttpResponseMessage Response = null;
var jsonBody = new SubscriptionJson();
jsonBody.CallBack.Address = ReceiverHost + ":" + MalPort.ToString();
jsonBody.CallBack.Method = "POST";
jsonBody.Type = "recognition";
var filter = new FilterProperty
{
Channels = new int[] { 0 },
DecisionComposition = new string[] { "Plate", "Channel" },
ImagesComposition = new string[] { },
};
jsonBody.Filter = JsonConvert.SerializeObject(filter);
string serObj = JsonConvert.SerializeObject(jsonBody);
Debug.Print(serObj);
//var body = Encoding.UTF8.GetBytes(serObj);
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(endpoint),
Content = new StringContent(serObj, Encoding.UTF8, "application/json")
};
var ResponseTask = httpClient.SendAsync(request);
Response = await ResponseTask;
string ResultJson = await Response.Content.ReadAsStringAsync();
Debug.WriteLine(ResultJson);
return true;
}
I think, than reason is in headers, but i couldn't do it. Help, please. I try use post method, send method "application/json" headers, / headers. I also trying string content, binary content, but nothing worked, i'm still have 406 error in Responce Object (and Empty ResultJson). I do not mind doing the first option, but I need async/await.
question from:
https://stackoverflow.com/questions/66068560/c-sharp-difference-between-httpwebrequest-and-httpclient 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…