当前位置: 移动技术网 > IT编程>开发语言>c# > C#请求http向网页发送接收数据的方法

C#请求http向网页发送接收数据的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了c#请求http向网页发送数据、网页接收,供大家参考,具体内容如下

首先,我们需要的是什么东西?

用post方式请求http,给网页传输数据,网页接收到数据之后,把数据存储到数据库中。

1.首先请求http,建立连接,把转码过的数据传输过去

2.网页接收数据,在转码之后存储到数据库

3.网页返回一个东西给传输方,表示我们已经接收到数据了

同样,我们请求http也是用的控制台模拟的

static void main(string[] args)
{
  string result = post("http://localhost:5534/home/tourl", "家庭");
  console.writeline(result);
  console.readkey();
}
/// <summary> 
    /// 指定post地址使用get 方式获取全部字符串 
    /// </summary> 
    /// <param name="url">请求后台地址</param> 
    /// <param name="content">post提交数据内容(utf-8编码的)</param> 
    /// <returns>结果</returns> 
    public static string post(string url, string content)
    {
      //申明一个容器result接收数据
      string result = "";
      //首先创建一个httpwebrequest,申明传输方式post
      httpwebrequest req = (httpwebrequest)webrequest.create(url);
      req.method = "post";
      req.contenttype = "application/x-www-form-urlencoded";

      //添加post参数
      byte[] data = encoding.utf8.getbytes(content);
      req.contentlength = data.length;
      using (stream reqstream = req.getrequeststream())
      {
        reqstream.write(data, 0, data.length);
        reqstream.close();
      }

      //申明一个容器resp接收返回数据
      httpwebresponse resp = (httpwebresponse)req.getresponse();
      stream stream = resp.getresponsestream();
      //获取响应内容 
      using (streamreader reader = new streamreader(stream, encoding.utf8))
      {
        result = reader.readtoend();
      }
      return result;
    }

然后,在controller里面有个tourl用于接收数据

public actionresult tourl()
    {
      string result = "";
      string jsonstr = "", line;
      try
      {

        stream streamresponse = request.inputstream;
        streamreader streamread = new streamreader(streamresponse, encoding.utf8);

        while ((line = streamread.readline()) != null)
        {
          jsonstr += line;
        }
        streamresponse.close();
        streamread.close();

        result = jsonstr;
      }
      catch (exception ex)
      {
        result = "msg-数据发布(in)异常:" + ex.message;
      }
      service service = new service();
      //调用addcatagorys方法,把数据添加进去
      service.addcatagorys(result);
      //再调用getcatas方法,获取到分类列表
      list<catagory> list = service.getcatagories();
      //找到分类列表最后一个分类,也就是刚刚添加的分类
      catagory catagory = list[list.count - 1];
      //返回json
      //return json(catagory)

      //返回一个id,content()里面是string类型,所以要把int转为string类型
      return content(catagory.id.tostring());
    }

这里其实相当于两个人打电话,你在跟我打电话的时候,按理来说不会再跟其他人打电话呗。

所以这里return content(catagory.id.tostring());表示将返回的id再返还给控制台,也就是传输方,让传输方知道我们接收到你传输过来的数据,并且把它保存到数据库里面了。

注:此篇随笔只供参考使用,而且也有很多小瑕疵,最主要的不是代码,逻辑才是最重要的。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网