Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

httprequest - C# difference between HttpWebRequest and HttpClient

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...