欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解c# .net core 下的网络请求

程序员文章站 2023-11-18 17:06:28
本文章是在vs2017的环境下,.net core 1.1版本以上。 在这期间,由于.net core 并不基于iis,我们的过去的网络请求代码在.net core框架下...

本文章是在vs2017的环境下,.net core 1.1版本以上。

在这期间,由于.net core 并不基于iis,我们的过去的网络请求代码在.net core框架下,有可能会出现不兼容,报错的现象。这里大致介绍下在.net core 下如何进行http请求,主要仍然是get和post方法,有错误的地方,欢迎指正!

先来说post,post我实现了三种方法,前两种基于的原理是完全一致的,后面的有些小小的差异,但他们的本质都是http请求,本质上是无区别的,只是实现方法有所不同。

废话不多说,上代码:

post异步方法:

 /// <summary>
    /// 异步请求post(键值对形式,可等待的)
    /// </summary>
    /// <param name="uri">网络基址("http://localhost:59315")</param>
    /// <param name="url">网络的地址("/api/umeng")</param>
    /// <param name="formdata">键值对list<keyvaluepair<string, string>> formdata = new list<keyvaluepair<string, string>>();formdata.add(new keyvaluepair<string, string>("userid", "29122"));formdata.add(new keyvaluepair<string, string>("umengids", "29122"));</param>
    /// <param name="charset">编码格式</param>
    /// <param name="mediatype">头媒体类型</param>
    /// <returns></returns>
    public async task<string> httppostasync(string uri, string url, list<keyvaluepair<string, string>> formdata = null, string charset = "utf-8", string mediatype = "application/x-www-form-urlencoded")
    {
      
      string tokenuri = url;
      var client = new httpclient();
      client.baseaddress = new uri(uri);
      httpcontent content = new formurlencodedcontent(formdata);
      content.headers.contenttype = new mediatypeheadervalue(mediatype);
      content.headers.contenttype.charset = charset;
      for (int i = 0; i < formdata.count; i++)
      {
        content.headers.add(formdata[i].key, formdata[i].value);
      }
      
      httpresponsemessage resp = await client.postasync(tokenuri, content);
      resp.ensuresuccessstatuscode();
      string token = await resp.content.readasstringasync();
      return token;
    }

post同步方法:

/// <summary>
    /// 同步请求post(键值对形式)
    /// </summary>
    /// <param name="uri">网络基址("http://localhost:59315")</param>
    /// <param name="url">网络的地址("/api/umeng")</param>
    /// <param name="formdata">键值对list<keyvaluepair<string, string>> formdata = new list<keyvaluepair<string, string>>();formdata.add(new keyvaluepair<string, string>("userid", "29122"));formdata.add(new keyvaluepair<string, string>("umengids", "29122"));</param>
    /// <param name="charset">编码格式</param>
    /// <param name="mediatype">头媒体类型</param>
    /// <returns></returns>
    public string httppost(string uri, string url, list<keyvaluepair<string, string>> formdata = null, string charset = "utf-8", string mediatype = "application/x-www-form-urlencoded")
    {      
      string tokenuri = url;
      var client = new httpclient();
      client.baseaddress = new uri(uri);
      httpcontent content = new formurlencodedcontent(formdata);
      content.headers.contenttype = new mediatypeheadervalue(mediatype);
      content.headers.contenttype.charset = charset;
      for (int i = 0; i < formdata.count; i++)
      {
        content.headers.add(formdata[i].key, formdata[i].value);
      }

      var res = client.postasync(tokenuri, content);
      res.wait();
      httpresponsemessage resp = res.result;
      
      var res2 = resp.content.readasstringasync();
      res2.wait();

      string token = res2.result;
      return token;
    }

遗憾的是,同步方法也是基于异步实现的,个人认为这样做会加大系统开销。如果各位有其他的高效实现,请不吝赐教!

接下来是通过流的方式进行post:

public string post(string url, string data, encoding encoding, int type)
    {
      try
      {
        httpwebrequest req = webrequest.createhttp(new uri(url));
        if (type == 1)
        {
          req.contenttype = "application/json;charset=utf-8";
        }
        else if (type == 2)
        {
          req.contenttype = "application/xml;charset=utf-8";
        }
        else
        {
          req.contenttype = "application/x-www-form-urlencoded;charset=utf-8";
        }

        req.method = "post";
        //req.accept = "text/xml,text/javascript";
        req.continuetimeout = 60000;

        byte[] postdata = encoding.getbytes(data);
        stream reqstream = req.getrequeststreamasync().result;
        reqstream.write(postdata, 0, postdata.length);
        reqstream.dispose();

        var rsp = (httpwebresponse)req.getresponseasync().result;
        var result = getresponseasstring(rsp, encoding);
        return result;
        
      }
      catch (exception ex)
      {
        throw;
      }
    }

private string getresponseasstring(httpwebresponse rsp, encoding encoding)
    {
      stream stream = null;
      streamreader reader = null;

      try
      {
        // 以字符流的方式读取http响应
        stream = rsp.getresponsestream();
        reader = new streamreader(stream, encoding);
        return reader.readtoend();
      }
      finally
      {
        // 释放资源
        if (reader != null) reader.dispose();
        if (stream != null) stream.dispose();
        if (rsp != null) rsp.dispose();
      }
    }

这种方式的post还是将数据写入到流里面,进行post,之所以写前两个key-value的形式,是为了符合java或者oc的风格,在c#书写的webapi中,由于接收形式是{=value}而不是{key=value}(由webapi的性质决定),后续我会说如何在webapi中接收(key-value)的形式,适当避免.net后台人员与android和ios的矛盾,从而达到**社会的长治久安。

接下来是get,同样同步异步都是由异步实现的,还请各位看官轻喷。

get:

 /// <summary>
    /// 异步请求get(utf-8)
    /// </summary>
    /// <param name="url">链接地址</param>    
    /// <param name="formdata">写在header中的内容</param>
    /// <returns></returns>
    public static async task<string> httpgetasync(string url, list<keyvaluepair<string, string>> formdata = null)
    {
      httpclient httpclient = new httpclient();
      httpcontent content = new formurlencodedcontent(formdata);
      if (formdata != null)
      {
        content.headers.contenttype = new mediatypeheadervalue("application/x-www-form-urlencoded");
        content.headers.contenttype.charset = "utf-8";
        for (int i = 0; i < formdata.count; i++)
        {
          content.headers.add(formdata[i].key, formdata[i].value);
        }
      }
      var request = new httprequestmessage()
      {
        requesturi = new uri(url),
        method = httpmethod.get,
      };
      for (int i = 0; i < formdata.count; i++)
      {
        request.headers.add(formdata[i].key, formdata[i].value);
      }
      var resp = await httpclient.sendasync(request);
      resp.ensuresuccessstatuscode();
      string token = await resp.content.readasstringasync();

      return token;
    }

 /// <summary>
    /// 同步get请求
    /// </summary>
    /// <param name="url">链接地址</param>    
    /// <param name="formdata">写在header中的键值对</param>
    /// <returns></returns>
    public string httpget(string url, list<keyvaluepair<string, string>> formdata = null)
    {
      httpclient httpclient = new httpclient();
      httpcontent content = new formurlencodedcontent(formdata);
      if (formdata != null)
      {
        content.headers.contenttype = new mediatypeheadervalue("application/x-www-form-urlencoded");
        content.headers.contenttype.charset = "utf-8";
        for (int i = 0; i < formdata.count; i++)
        {
          content.headers.add(formdata[i].key, formdata[i].value);
        }
      }
      var request = new httprequestmessage()
      {
        requesturi = new uri(url),
        method = httpmethod.get,
      };
      for (int i = 0; i < formdata.count; i++)
      {
        request.headers.add(formdata[i].key, formdata[i].value);
      }
      var res = httpclient.sendasync(request);
      res.wait();
      var resp = res.result;
      task<string> temp = resp.content.readasstringasync();
      temp.wait();
      return temp.result;
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。