简体   繁体   English

如何将 HttpWebRequest 更改为 Httpclient

[英]How to change HttpWebRequest to Httpclient

I'm having trouble translating the code fragment in my example to http client.我在将示例中的代码片段转换为 http 客户端时遇到问题。 every time the code breaks in the timestamp calculation.每次代码在时间戳计算中中断。 can you help me with this?你能帮我吗? What I want to do is to write the same request using current technology.我想做的是使用当前技术编写相同的请求。 for example httpclient example code例如 httpclient 示例代码

    public byte[] GetTimeStamp(TimeStampModel model)
    {
        TimeStampRequestGenerator tsrq = new TimeStampRequestGenerator();
        tsrq.SetCertReq(model.certReq);
        BigInteger nonce = BigInteger.ValueOf(DateTime.Now.Ticks);
        TimeStampRequest tsr = tsrq.Generate(model.digestMethod.Oid, model.hash, nonce);
        byte[] data = tsr.GetEncoded();


        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_url);
        req.Method = "POST";
        req.ContentType = "application/timestamp-query";
        req.ContentLength = data.Length;

        if (!string.IsNullOrEmpty(_user) && !string.IsNullOrEmpty(_password))
        {
            string auth = string.Format("{0}:{1}", _user, _password);
            req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(auth), Base64FormattingOptions.None);
        }

        Stream reqStream = req.GetRequestStream();
        reqStream.Write(data, 0, data.Length);
        reqStream.Close();

        HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        if (res.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("Sunucu geçersiz bir yanıt döndürdü");
        }
        else
        {
            Stream resStream = new BufferedStream(res.GetResponseStream());
            TimeStampResponse tsRes = new TimeStampResponse(resStream);
            resStream.Close();

            tsRes.Validate(tsr);
            if (tsRes.TimeStampToken == null)
            {
                throw new Exception("Sunucu herhangi bir zaman damgası döndürmedi");
            }

            return tsRes.TimeStampToken.GetEncoded();
        }
    }

I have a generic httpclientwrapper class. hope it helps我有一个通用的 httpclientwrapper class。希望它有帮助

public async Task<TResponse> Post<TRequest, TResponse>(TRequest request, string urlToSend, string token)
    {
        try
        {


            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(_url);
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, token ?? "");
                var serialized = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
                var httpResponseMessage = await httpClient.PostAsync(urlToSend, serialized);
                //httpResponseMessage.EnsureSuccessStatusCode();
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    var resStr = httpResponseMessage.Content.ReadAsStringAsync().Result;
                    var responseString = JsonConvert.DeserializeObject<TResponse>(httpResponseMessage.Content.ReadAsStringAsync().Result);

                    return responseString;
                }
                else if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.BadRequest)
                {
                    var errorRes = httpResponseMessage.Content.ReadAsStringAsync().Result;
                    throw new Exception(errorRes);
                }
                throw new Exception(httpResponseMessage.ReasonPhrase);
            }
        }
        catch (Exception e)
        {

            throw new Exception(e.Message);
        }
    }

In this code,在这段代码中,

- I got token from constructor. - 我从构造函数那里得到了令牌。 Don't confuse with it. 不要与它混淆。

  • I use with asynchronous Tasks.我使用异步任务。
  • The TRequest is used to make generic any request class object. TRequest 用于发出通用的任何请求 class object。
  • TResponse is the class who gets response from remoteurl. TResponse 是从 remoteurl 得到响应的 class。 You can use any class.您可以使用任何 class。
  • I suppose you do not have to serialize object, also you have to set content type.我想你不必序列化 object,你也必须设置内容类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM