天天看點

C# Http請求(WebClient,HttpWebRequest)

WebClient Post Get送出資料

using (WebClient client = new WebClient())
{
          client.Headers["version"] = "1.0";//http header 填入屬性
          client.Headers["APIToken"] = token;
          string datas = "sdfdsfsdfsf";//Post送出的資料
          string strs = GetStrs(order.OrderId);//擷取xml文檔
          //resul是傳回的結果
          string resul = System.Text.Encoding.UTF8.GetString(client.UploadData("請求位址", "POST", Encoding.UTF8.GetBytes(datas)));
          //Client.DownloadFile(url, paths);//url位址,paths寫入檔案的位址
} 
           

1. string postString = "arg1=a&arg2=b";//這裡即為傳遞的參數,可以用工具抓包分析,也可以自己分析,主要是form裡面每一個name都要加進來  

2. byte[] postData = Encoding.UTF8.GetBytes(postString);//編碼,尤其是漢字,事先要看下抓取網頁的編碼方式  

3. string url = "http://localhost/register.php";//位址  

4. WebClient webClient = new WebClient();  

5. webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必須加的header,如果改為GET方式的話就去掉這句話即可    

    client.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8" );

6. byte[] responseData = webClient.UploadData(url, "POST", postData);//得到傳回字元流  

7. string srcString = Encoding.UTF8.GetString(responseData);//解碼 

擷取傳回500失敗的資訊 響應的資訊

服務端程式産生緻命錯誤,http 表現為錯誤号 500,伺服器拒絕響應

C# Http請求(WebClient,HttpWebRequest)

代碼

try
                    {
                        using (WebClient client = new WebClient())
                        {
                            client.Headers.Add( "Content-Type", "application/x-www-form-urlencoded" );
                            string result = Encoding .UTF8.GetString(client.UploadData(Helper.CountryUrl, Encoding.UTF8.GetBytes(Helper .ReaquestCountryData())));
                            XmlDocument document = new XmlDocument();
                            document.LoadXml(result);
                           
                            XmlNodeList xnlis = document.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes;
                            List<Service.country > list = new List<Service. country>();
                            foreach (XmlNode x in xnlis)
                            {
                                list.Add( new Service.country () { enName = x.GetAttributeValue("enName") });
                            }
                            return list.ToArray();
                        }
                    }
                    catch(WebException e)
                    {
                        Stream stream = e.Response.GetResponseStream();
                        byte[] buf = new byte[e.Response.ContentLength];
                        stream.Read(buf, 0, buf.Length);
                        string str = Encoding .UTF8.GetString(buf);
                       
                    }
           

//HttpWebRequest

//Get請求

public static string GetUrltoHtml(string Url,string type)
        {
            try
            {
                System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);
                // Get the response instance.
                System.Net.WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream = wResp.GetResponseStream();
                // Dim reader As StreamReader = New StreamReader(respStream)
                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (System.Exception ex)
            {
                //errorMsg = ex.Message;
            }
            return "";
        } 
           

//Post請求

///<summary>
        ///采用https協定通路網絡
        ///</summary>
        ///<param name="URL">url位址</param>
        ///<param name="strPostdata">發送的資料</param>
        ///<returns></returns>
        public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding)
        {
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "post";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] buffer = encoding.GetBytes(strPostdata);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using( StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
              {
                   return reader.ReadToEnd();
              }
        }