簡體   English   中英

從HttpWebRequest切換到HttpClient

[英]Switching from HttpWebRequest to HttpClient

我試圖將一些方法從httpwebrequest轉移到httpclient。 我完成了大部分工作,但堅持使用這一項。 有人可以幫助實現這一目標。

string url = someurl;
HttpWebRequest request = CreateRequest(url);

request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;

string body = @"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();

response = (HttpWebResponse)request.GetResponse(); 

我需要使用HttpClient轉換此方法。

這就是我嘗試過的。

  string url = someurl;
            var client = new HttpClient();;


            client.DefaultRequestHeaders
                  .Accept
                  .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header

            //request.ContentType = "application/x-www-form-urlencoded";
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,url);

            string body = @"somestring here...";

            var content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
            request.Content = content;


            var ss = client.PostAsync(url,content).Result;
            string str2 = await ss.Content.ReadAsStringAsync();

我沒有讓這部分工作。

 string body = @"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();

這是我大部分時間都在使用的示例客戶端類。 您可以使用PostAsync或SendAsync

public class RestClient
{
    public bool IsDisposed { get; private set; }
    public HttpClient BaseClient { get; private set; }

    private readonly string jsonMediaType = "application/json";

    public RestClient(string hostName, string token, HttpClient client)
    {
        BaseClient = client;
        BaseClient.BaseAddress = new Uri(hostName);
        BaseClient.DefaultRequestHeaders.Add("Authorization", token);
    }

    public async Task<string> PostAsync(string resource, string postData)
    {
        StringContent strContent = new StringContent(postData, Encoding.UTF8, jsonMediaType);
        HttpResponseMessage responseMessage = await BaseClient.PostAsync(resource, strContent).ConfigureAwait(false);
        responseMessage.RaiseExceptionIfFailed();
        return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
    }

    public async Task<string> SendAsync(HttpMethod method, string resource, string token, string postData)
    {
        var resourceUri = new Uri(resource, UriKind.Relative);
        var uri = new Uri(BaseClient.BaseAddress, resourceUri);
        HttpRequestMessage request = new HttpRequestMessage(method, uri);
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        if (!string.IsNullOrEmpty(postData))
        {
            request.Content = new StringContent(postData, Encoding.UTF8, jsonMediaType);
        }

        HttpResponseMessage response = BaseClient.SendAsync(request).Result;
        response.RaiseExceptionIfFailed();
        return await response.Content.ReadAsStringAsync();
    }

    protected virtual void Dispose(bool isDisposing)
    {
        if (IsDisposed)
        {
            return;
        }
        if (isDisposing)
        {
            BaseClient.Dispose();
        }
        IsDisposed = true;
    }

    public virtual void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~RestClient()
    {
        Dispose(false);
    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM