Web标题集合Xamarin上的HttpWebRequest [英] WebHeaderCollection & HttpWebRequest on Xamarin

查看:124
本文介绍了Web标题集合Xamarin上的HttpWebRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将项目从Mac上的Xamarin Studio移植到Windows 7上的Visual Studio 2012. 在Mac和XS上都可以正常工作.在Visual Studio 2012上,我遇到了两个问题:

I'm trying to port my project from Xamarin Studio on Mac to Visual Studio 2012 on Windows 7. On Mac and XS works all fine. On VisualStudio 2012 i've those 2 problems:

错误3'System.Net.WebHeaderCollection'不包含定义 对于添加",没有扩展方法添加"接受第一个参数 可以找到"System.Net.WebHeaderCollection"类型(您是否丢失了 使用指令或程序集 参考?)C:\ Users \ user \ Documents \ Visual Studio 2012 \ Projects \ MyProject \ MyProject.Core \ Services \ MyProjectService.cs

Error 3 'System.Net.WebHeaderCollection' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Net.WebHeaderCollection' could be found (are you missing a using directive or an assembly reference?) C:\Users\user\Documents\Visual Studio 2012\Projects\MyProject\MyProject.Core\Services\MyProjectService.cs

错误4'System.Net.HttpWebRequest'不包含以下内容的定义: "GetResponse",没有扩展方法"GetResponse"接受第一个 可以找到类型为'System.Net.HttpWebRequest'的参数 缺少using指令或程序集 参考?)C:\ Users \ user \ Documents \ Visual Studio 2012 \ Projects \ MyProject \ MyProject.Core \ Services \ MyProjectService.cs

Error 4 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?) C:\Users\user\Documents\Visual Studio 2012\Projects\MyProject\MyProject.Core\Services\MyProjectService.cs

在该代码上:

    var request = WebRequest.Create("https://www.myaddress.com/test/") as HttpWebRequest;
    request.Method = "GET";
    request.Accept = "application/json";
    request.Headers.Add(HttpRequestHeader.Cookie,"mycookievalue");

    // Get response  
    using (var response = request.GetResponse() as HttpWebResponse)
    {
        // Get the response stream  
        var reader = new StreamReader(response.GetResponseStream());
        content = reader.ReadToEnd();
    }

我该如何解决?

推荐答案

到目前为止,您提到的内容尚未实现. 但是没关系.他们仍然做得很好!

There is no implementation of the things mentioned by you so far. But that's ok. They still do their work great!

回答您的问题.

错误3.是.当前,您只能使用Headers ["key"] = value.但.并非针对每个标头.我试图在其中放置" Content-Length "(因为也没有实现"ContentLength"属性),但是出现了受限标头"异常. 但是,请求 POST 为我成功完成了处理,所以我放手了.

Error 3. Yes. Currently you can use only Headers["key"] = value. But. Not for every header. I was trying to put "Content-Length" there (as there is no "ContentLength" property implemented as well), but got "restricted headers" exception. However, Request POST processed successfully for me, so I let it go.

错误4.是.没有这样的方法. (以同样的方式,因为没有" GetRequestStream "(例如,如果您想将POST数据写入请求流).好消息是,分别有BeginGetResponse和 BeginGetRequestStream ,而C#操作方法简化了所有厨房.

Error 4. Yes. There is no such method. (The same way, as there is no "GetRequestStream" (For instance, if you want to write POST data to request stream)). Good news is that there are BeginGetResponse and BeginGetRequestStream respectively, and C# action methods simplify all that kitchen.

(此外,我敢肯定,这对于异步实践的一般理解非常有用).

基本示例可以在 Microsoft官方文档中找到.

但是要执行操作,我使用了以下内容:

But to do it with actions I used the following:

    public void MakeRequest(string url, string verb, Dictionary<string, string> requestParams,
        Action<string> onSuccess, Action<Exception> onError)
    {
        string paramsFormatted;

        if (verb == "GET")
        {
            paramsFormatted = string.Join("&", requestParams.Select(x => x.Key + "=" + Uri.EscapeDataString(x.Value)));
            url = url + (string.IsNullOrEmpty(paramsFormatted) ? "" : "?" + paramsFormatted);
        }
        else
        {
            // I don't escape parameters here,
            // as Uri.EscapeDataString would throw exception if the parameter length
            // is too long, so you must control that manually before passing them here
            // for instance to convert to base64 safely
            paramsFormatted = string.Join("&", requestParams.Select(x => x.Key + "=" + (x.Value)));
        }

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = verb;

        requestParams = requestParams ?? new Dictionary<string, string>();

        Action goRequest = () => MakeRequest(request, 
            response =>
            {
                onSuccess(response);
            },
            error =>
            {
                if (onError != null)
                {
                    onError(error);
                }
            });

        if (request.Method == "POST")
        {
            request.BeginGetRequestStream(ar =>
            {
                using (Stream postStream = request.EndGetRequestStream(ar))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(paramsFormatted);
                    postStream.Write(byteArray, 0, paramsFormatted.Length);
                }
                goRequest();
            }, request);
        }
        else // GET
        {
            goRequest();
        }
    }

    private void MakeRequest(HttpWebRequest request, Action<string> onSuccess, Action<Exception> onError)
    {
        request.BeginGetResponse(token =>
        {
            try
            {
                using (var response = request.EndGetResponse(token))
                {
                    using (var stream = response.GetResponseStream())
                    {
                        var reader = new StreamReader(stream);
                        onSuccess(reader.ReadToEnd());
                    }
                }
            }
            catch (WebException ex)
            {
                onError(ex);
            }
        }, null);
    }

这篇关于Web标题集合Xamarin上的HttpWebRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆