C#最简单的POST提交

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Diagnostics;//Trace.WriteLine
using System.Net;
using System.IO;

namespace ddtest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //POST /index.php HTTP/1.1
            //Accept: text/html, application/xhtml+xml, */*
            //X-HttpWatch-RID: 3202-10097
            //Referer: http://walkingleaf.sinaapp.com/test.html
            //Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3
            //User-Agent: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
            //Content-Type: application/x-www-form-urlencoded
            //Accept-Encoding: gzip, deflate
            //Host: walkingleaf.sinaapp.com
            //Content-Length: 23
            //DNT: 1
            //Connection: Keep-Alive
            //Cache-Control: no-cache
            //Cookie: saeut=222.190.117.217.1415363433988703

            //yourname=11&yourage=111
            string strPost="yourname=hello&yourage=world";//提交的数据
            Encoding encode = Encoding.GetEncoding("utf-8");//网页编码==Encoding.UTF8
            byte[] bt=encode.GetBytes(strPost);
            HttpWebRequest req=(HttpWebRequest)WebRequest.Create(new Uri(@"http://walkingleaf.sinaapp.com/index.php"));
            req.Method="POST";
            req.Referer=@"http://walkingleaf.sinaapp.com/test.html";
            req.UserAgent=" Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko";
            req.ContentType="application/x-www-form-urlencoded";
            req.Accept="text/html, application/xhtml+xml, */*";
            req.Headers.Add("X-HttpWatch-RID","3202-10097");
            req.Headers.Add("Accept-Language","zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3");

            Stream streamReq=req.GetRequestStream();
            streamReq.Write(bt,0,bt.Length);
            streamReq.Close();
            HttpWebResponse res=(HttpWebResponse)req.GetResponse();
            Stream streamRes=res.GetResponseStream();
            StreamReader reader=new StreamReader(streamRes,encode);
            string result=reader.ReadToEnd();

            Trace.WriteLine(result);

        }
    }
}

你可能感兴趣的:(C#编程)