1. 程式人生 > >C# 模擬瀏覽器的POST/GET請求

C# 模擬瀏覽器的POST/GET請求

本文部分來源其它部落格的摘取,如有侵權請留言刪除。

本文為模擬瀏覽器的POST/GET請求,向web應用發起命令,具體程式碼可應用在網路爬蟲,病毒機器人等方面。

下面是主要用到的一些程式碼段:

1.構建HTTPRequest請求/POST/GET

private HttpWebRequest createRequest(String url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //Post請求方式  
            request.Method = "POST";
            //內容型別 
            request.ContentType = "application/json";
            if (token != null&&token!="")
                request.Headers.Add("Authorization","Bearer " + token);
            return request;
        }

2.向Request寫入引數


        public String writeParas(HttpWebRequest request,string jsonParas)
        {
            byte[] payload;
            //將Json字串轉化為位元組  
            payload = System.Text.Encoding.UTF8.GetBytes(jsonParas);
            //設定請求的ContentLength   
            request.ContentLength = payload.Length;
            //傳送請求,獲得請求流 
            request.ServicePoint.Expect100Continue = false;
            //HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            Stream writer = null;

            try
            {
                writer = request.GetRequestStream();//獲取用於寫入請求資料的Stream物件 
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("連線伺服器失敗!");
            }

            //將請求引數寫入流 
            writer.Write(payload, 0, payload.Length);
            writer.Close();//關閉請求流 

            HttpWebResponse response;
            try
            {
                //獲得響應流 
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }

            Stream s = response.GetResponseStream();

            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();

            return postContent;
        }

3.解析返回值

如果是規則的json字串,比較好解析

                //字串轉json物件
                JObject jsonData = JObject.Parse(resp);


                //從json物件中取值
                JObject data = (JObject)jsonData["data"];


                //當json物件取值為物件列表,使用JArray接收,foreach遍歷,即可得到每個物件
                JArray droneL = (JArray)data["drone"];
                foreach (JObject d in droneL)
                {
                }

如果是普通字串,使用字串擷取函式.

3.1.根據單個分隔字元用split擷取

string st="GT123_1";
 

string[] sArray=st.split("_");

即可得到sArray[0]="GT123",sArray[1]="1";

3.2.利用多個字元來分隔字串

string str = "GTAZB_JiangjBen_123";
string[] sArray = str.Split(new char[2] { 'j', '_' });
foreach(string e in sArray)
{
Console.WriteLine(e);
}

得到sArray[0]="GTAZB",sArray[1]="Jiang",sArray[2]="Ben",sArray[3]="123";

3.3根據字串或字串組來擷取字串

string str = "GTAZB_JiangjBen_123";
string[] sArray = str.Split( new string[]{"Ji","jB"}, StringSplitOptions.RemoveEmptyEntries);
foreach(string e in sArray)
{
Console.WriteLine(e);
}

得到sArray[0]="GTAZB_",sArray[1]="ang",sArray[2]="en_123";

3.4提取字串中的第i個字元開始的長度為j的字串;特別的利用IndexOf找出目的欄位所在位置;

string str = "GTAZB_JiangjBen_123";
int start=3,length=8; 
Console.WriteLine(str.Substring(start-1, length));

輸出得到AZB_Jian。

3.5提取字串中右數長度為i的字串

string str = "GTAZB_JiangjBen_123";
string tSt;
int i=5;
tSt = str.Substring(str.Length - i); 
Console.WriteLine(tSt);

輸出n_123;

3.6 取字串的前i個字元
  

 str=str.Substring(0,i); // or  str=str.Remove(i,str.Length-i); 

3.7 去掉字串的前i個字元:
  

 str=str.Remove(0,i);  // or str=str.Substring(i);