WebHeaderCollection &Xamarin 上的 HttpWebRequest [英] WebHeaderCollection & HttpWebRequest on Xamarin

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

问题描述

我正在尝试将我的项目从 Mac 上的 Xamarin Studio 移植到 Windows 7 上的 Visual Studio 2012.在 Mac 和 XS 上一切正常.在 VisualStudio 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"(您是否缺少using 指令或程序集参考?) C:UsersuserDocumentsVisual Studio2012ProjectsMyProjectMyProject.CoreServicesMyProjectService.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:UsersuserDocumentsVisual Studio 2012ProjectsMyProjectMyProject.CoreServicesMyProjectService.cs

错误 4 'System.Net.HttpWebRequest' 不包含对'GetResponse' 并且没有扩展方法 'GetResponse' 接受第一个可以找到System.Net.HttpWebRequest"类型的参数(你是缺少 using 指令或程序集参考?) C:UsersuserDocumentsVisual Studio2012ProjectsMyProjectMyProject.CoreServicesMyProjectService.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:UsersuserDocumentsVisual Studio 2012ProjectsMyProjectMyProject.CoreServicesMyProjectService.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"属性),但是得到了restricted headers"异常.但是,请求 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# action 方法 简化了所有厨房.

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.

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

基本示例可以在 微软官方文档.

但是要通过操作来做到这一点,我使用了以下操作:

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);
    }

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

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