使用HttpClient进行Xamarin PCL

时间:2015-07-29 22:36:49

标签: c# xamarin portable-class-library

我正在Xamarin中创建一个PCL,它使用Microsoft.Net.Http Nuget包作为HttpClient类。我使用HttpClient将音频文件发布到Web API。到目前为止,这对我来说效果很好,但是现在我在尝试将文件传输到API时遇到了麻烦。 API在其文档中说要添加set" Transfer-encoding"标题是" chunked"为了接受文件的流媒体。我不能像我对其他标题一样手动添加此标题,而是从HttpClient的属性设置它。问题是,当我调用HttpClient.PostAsync()时,它会抛出异常,因为HttpWebRequest的SendChunk属性不是True。我假设HttpWebRequest对象是由HttpClient创建的,但我不知道如何将SendChunk属性设置为True。当我自己创建HttpWebRequest对象时,即使它是公共属性,也无法访问SendChunk属性。我猜它与PCL有关,但SeundChunk属性确实出现在Microsoft.Net.Http程序集中。

简而言之,我需要获得标题"转码编码:chunked"进入我的HttpClient标题,但不能。如果某些属性不可用,我如何添加此标题,因为我在PCL中工作?

public async Task<string> PostAsync(string url, Stream content, Dictionary<string,string> requestHeaders, Dictionary<string,string> contentHeaders)
    {
        var httpClient = new System.Net.Http.HttpClient();
        var httpContent = new System.Net.Http.StreamContent(content);

        httpClient.Timeout = TimeSpan.FromSeconds(20);
        httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;

        if (requestHeaders != null)
        {
            foreach (var headerName in requestHeaders.Keys)
            {
                httpClient.DefaultRequestHeaders.Add(headerName, requestHeaders[headerName]);
            }
        }
        if (contentHeaders != null)
        {
            foreach (var headerName in contentHeaders.Keys)
            {
                httpContent.Headers.Add(headerName, contentHeaders[headerName]);
            }
        }

        HttpResponseMessage response = null;

        try
        {
            response = await httpClient.PostAsync(url, httpContent);
        }

编辑:

我已将代码更新为

             HttpClientHandler handler = new HttpClientHandler();

        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(handler);
        httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);

        var httpContent = new System.Net.Http.StreamContent(content);

        request.Content = httpContent;

        if (handler.SupportsTransferEncodingChunked())
        {
            request.Headers.TransferEncodingChunked = true;
        }

        HttpResponseMessage response = null;


            response = await httpClient.SendAsync(request);

SendAsync抛出一个异常,说&#34; System.Net.ProtocolViolationException:SendChunked应为true&#34;。我在此帖http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx之后对我的代码进行了建模。

2 个答案:

答案 0 :(得分:1)

我正在尝试处理类似的情况。我遇到了一些可能有用的选项。

ModernHTTPClient

或者这个 Rest Sharp

作为状态更新,我确实让ModernHTTPClient工作。我的解决方案虽然我不得不删除我的包文件夹的内容,然后安装该nuget包,然后恢复我的其他包。否则解决方案很简单

var httpClient = new HttpClient(new NativeMessageHandler());

答案 1 :(得分:0)

我在Xamarin论坛上找到了这个链接的手工库; https://forums.xamarin.com/discussion/25274/httpclient-in-pcl

Robert McLaws和Richard Beauchamp创作了一个名为PortableRest的Nuget Package。

它是一个从可移植类库(.NET 4.5,Silverlight 5,Windows Phone 8.x和Windows 8.x)中使用REST API的库。旨在与RestSharp部分插入兼容。

GitHub链接:https://github.com/AdvancedREI/PortableRest Nuget包在这里:https://www.nuget.org/packages/PortableRest

来源:https://forums.xamarin.com/discussion/25274/httpclient-in-pcl

要使用它:

var client = new RestClient { BaseUrl = Constants.API_BASE_URI };
var request = new RestRequest("Token", HttpMethod.Post, ContentTypes.FormUrlEncoded);
request.AddHeader("Accept", "application/json");
request.AddParameter("grant_type", "password", ParameterEncoding.UriEncoded);
request.AddParameter("username", userEntry.Text, ParameterEncoding.UriEncoded);
request.AddParameter("password", passwordEntry.Text, ParameterEncoding.UriEncoded);

var result = await client.SendAsync<AuthToken>(request);