zoukankan      html  css  js  c++  java
  • Winform 程序以POST形式访问网站

    本例介绍了Winform程序发送POST请求访问页面,主要使用到了HttpWebRequest和HttpWebResponse这两个对象。

    程序主要代码如下:

    代码
     1 using System.Net;
    2 using System.IO;
    3
    4
    5 //创建HttpWebRequest对象
    6 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://192.168.0.1");//目标主机ip地址
    7
    8 //模拟POST的数据
    9 string postData = string.Empty;
    10 postData += "user=" + "test1";
    11 postData += "&password=" + "123";
    12 Encoding utf8=Encoding.UTF8;
    13 byte[] data = utf8.GetBytes(postData);
    14
    15 //设置请求头信息
    16 string cookieheader = string.Empty;
    17 CookieContainer cookieCon = new CookieContainer();
    18 request.Method = "POST";
    19 //设置cookie,若没有可以不设置
    20 request.CookieContainer = cookieCon;
    21 request.ContentType = "application/x-www-form-urlencoded";
    22 request.ContentLength = data.Length;
    23 Stream newStream = request.GetRequestStream();
    24 //把请求数据 写入请求流中
    25 newStream.Write(data, 0, data.Length);
    26 newStream.Close();
    27
    28
    29 //获得HttpWebResponse对象
    30 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    31
    32 Console.Write("Content length is {0}", response.ContentLength + "\r\n");
    33 Console.Write("Content type is {0}", response.ContentType + "\r\n");
    34
    35 //获得响应流
    36 Stream receiveStream = response.GetResponseStream();
    37 StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
    38 //输入响应流信息
    39 Console.Write("Response stream received.\r\n");
    40 Console.Write(readStream.ReadToEnd() + "\r\n");
    41
    42 response.Close();
    43 receiveStream.Close();
    44 readStream.Close();
  • 相关阅读:
    Titanium环境搭建for mac
    MongoDB学习(二)MongoDB Java增删查改
    Titanium 列表显示TableView
    MongoDB学习(一)安装配置
    MongoDB学习(三)MongoDB shell 命令行的使用
    jsoup解析html
    C#中方法的参数四种类型(值参数、ref、out、params)详解
    ORM JPA 介绍及其使用
    Git Add提示LF would be replaced by CRLF的解决方法
    Spring Data JPA 介绍及使用
  • 原文地址:https://www.cnblogs.com/Johnny_Z/p/2348286.html
Copyright © 2011-2022 走看看