【问题标题】:Switching from HttpWebRequest to HttpClient从 HttpWebRequest 切换到 HttpClient
【发布时间】:2017-09-19 12:24:09
【问题描述】:

我正在尝试将一些方法从 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...请提供更多详细信息,说明哪个部分导致您出现问题。 (我们不知道CreateRequest 做了什么也无济于事。)
  • HttpClient 只有异步方法。您的代码是否是异步的,这样您就不需要阻塞异步调用(.Result、.Wait()..)?
  • 到目前为止你尝试过什么?本网站不是代码转换器
  • 我有一个blog post 使用HttpClient。底部是我用来整理的资源列表。网上有很多使用HttpClient的例子,但做得很好的例子不多。
  • 我已经更新了这个问题。非常感谢您的帮助。

标签: c# httpwebrequest httpclient


【解决方案1】:

这是我大部分时间使用的示例客户端类。您可以使用 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);
    }


}

【讨论】:

    猜你喜欢
    • 2022-12-30
    • 2023-04-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多