【问题标题】:How to use HttpWebRequest with async & await如何将 HttpWebRequest 与异步和等待一起使用
【发布时间】:2014-09-12 19:29:41
【问题描述】:

我也是 Xamarin 和 C# 的新手。我尝试使用一些信息向我的服务器发出 Http 请求。 一般来说,android Native a 使用 AsyncTask 和 HttpClient 。并构建一个 json 对象或名称值对,并将其加密以将信息与请求集成。 但是当我尝试对 xamarin 做同样的事情时,我遇到了一些问题。

  1. 如果我尝试导入命名空间

使用 System.Net.Http.HttpClient 比我的 xamarin 没有这个命名空间

  1. 由于上述问题,我尝试使用 HttpWebRequest。但是当我将它与 asyc 一起使用并等待时,我没有收到来自服务器的任何响应。

我是 xamarin 的新手,所以我不确定 async 和 await 关键字。 我读了很多文章,但没有运气:(

点击按钮我调用下面的方法

 public async Task<int> ValidateUser(){
    try{
     var request = HttpWebRequest.Create (URL);
     request.Method = "GET/POST";
     String postString = String.Format ("AAA ={0}&BBB={1}&CCC={2}", "111", 
                                          "222","333");

        byte[] postByte = Encoding.UTF8.GetBytes (postString);

        Stream st = request.GetRequestStream ();

        //I am reaching here
            Console.WriteLine("Check for Validity");

        request.ContentLength = postByte.Length;

        st.Write (postByte, 0, postByte.Length);

        st.Close ();
            Task<Stream> contentTask = request.GetRequestStreamAsync();
            Stream response = await contentTask;

            String str = response.ToString();

            // this is not getting printed in Console 
               Console.WriteLine("=====>>"+str);

      }
        catch (WebException exception) {
            string responseText;
            using (var reader = new StreamReader(exception.Response.GetResponseStream())) {
                responseText = reader.ReadToEnd ();
                Console.WriteLine ("====Dude Error"+responseText);
            }
        }catch(Exception e){

        }
        return 1;
    }

任何帮助将不胜感激

【问题讨论】:

  • 使用 HttpWebRequest 是个坏主意,相反,最好关注为什么没有 System.Net.Http.* 命名空间。最可能的原因是,您没有添加 System.Net.Http 作为对项目的引用。
  • 我尝试添加,但不是博士...请告诉我它是否不存在,如何集成到 xamarin

标签: android xamarin xamarin.android


【解决方案1】:

考虑使用 RestSharp,这是一个为 Xamarin 创建的组件,用于促进 Web 请求。 Click here 了解有关该组件的更多信息。它将促进有关 webrequesting 的分配(如序列化、自动返回类型检测......)

使用 restsharp,您的代码将如下所示:

public async Task<int> ValidateUser(){

     var client = RestClient (URL);
     var request = new RestRequest ("AAA ={0}&BBB={1}&CCC={2}", "111", 
                                          "222","333");

            client.ExecuteAsync (request, response => {

                    WebApiResponse webApiResponse = new WebApiResponse ();

                    webApiResponse.Content = response.Content;
                    webApiResponse.StatusCode = response.StatusCode;
                    webApiResponse.ResponseStatus = (WebApiResponseStatus)response.ResponseStatus;

                    return webApiResponse.Content;
                });         


        return -1

    }

【讨论】:

  • 感谢您的指导,但我认为应该是 client = new RestClient(URL);在 request= new RestClient(URL); 的地方
  • 我的道歉,我已经纠正了我的错误。如果您使用此答案,您能否通过单击带有两个箭头的数字旁边的 V 将其标记为正确答案?谢谢 :)
【解决方案2】:

使用 HttpWebRequest 是个坏主意,相反,最好专注于为什么没有 System.Net.Http.* 命名空间。恕我直言,最可能的原因是您没有添加 System.Net.Http 作为对项目的引用。

以下是将 System.Net.Http.* 添加到项目的方法。

在 Visual Studio 2013 中:

  • 打开解决方案
  • 打开项目
  • 打开解决方案资源管理器
  • 右键单击参考文献
  • 添加参考
  • 点击“搜索程序集”
  • 输入“Http”
  • 选择 System.Net.Http
  • 按“确定”

在 Xamarin Studio 中:

  • 打开解决方案
  • 打开项目
  • 打开解决方案资源管理器
  • 右键单击参考文献
  • 编辑参考文献
  • 输入“Http”
  • 选择 System.Net.Http
  • 按“确定”

之后在“使用 System.Net.Http;”时解析 System.Net.Http 应该没有问题

【讨论】:

  • 我尝试使用 System.Net.Http 进行上述操作;现在它向我展示了 HttpClient,谢谢弗兰克
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
相关资源
最近更新 更多