您好,登錄后才能下訂單哦!
本篇內容介紹了“HttpRequest Get和Post怎么調用其他頁面”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
復制代碼 代碼如下:
//Get請求方式
private string RequestGet(string Url)
{
string PageStr = string.Empty;//用于存放還回的html
Uri url = new Uri(Url);//Uri類 提供統一資源標識符 (URI) 的對象表示形式和對 URI 各部分的輕松訪問。就是處理url地址
try
{
HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(url);//根據url地址創建HTTpWebRequest對象
#region 參數設置
httprequest.Method = "get";
//---------------------------------------------設定一些參數(不必要可以)
//httprequest.KeepAlive = false;//持久連接設置為false
//httprequest.ProtocolVersion = HttpVersion.Version11;// 網絡協議的版本
//httprequest.Proxy = WebProxy.GetDefaultProxy();//服務器代理
//httprequest.ContentType = "application/x-www-form-urlencoded";//http 頭
//httprequest.AllowAutoRedirect = true;
//httprequest.MaximumAutomaticRedirections = 10;
//httprequest.Timeout = 30000;//設定超時十秒(毫秒)
//httprequest.UserAgent = "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1)"; //瀏覽器
//=================================================
#endregion
HttpWebResponse response = (HttpWebResponse)httprequest.GetResponse();//使用HttpWebResponse獲取請求的還回值
Stream steam = response.GetResponseStream();//從還回對象中獲取數據流
StreamReader reader = new StreamReader(steam, Encoding.GetEncoding("gb2312"));//讀取數據Encoding.GetEncoding("gb2312")指編碼是gb2312,不讓中文會亂碼的
PageStr = reader.ReadToEnd();
reader.Close();
}
catch (Exception e)
{
PageStr += e.Message;
}
return PageStr;
}
復制代碼 代碼如下:
//Post請求方式,于Get的方式寫法相似,所以解釋就些少一點了
private string RequestPost(string Url,string Context)//兩個參數分別是Url地址和Post過去的數據
{
string PageStr=string.Empty;
Uri url = new Uri(Url);
byte[] reqbytes=Encoding.ASCII.GetBytes(Context);
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "post";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = reqbytes.Length;
Stream stm = req.GetRequestStream();
stm.Write(reqbytes, 0, reqbytes.Length);
stm.Close();
HttpWebResponse wr = (HttpWebResponse)req.GetResponse();
Stream stream = wr.GetResponseStream();
StreamReader srd= new StreamReader(stream,Encoding.GetEncoding("gb2312"));
PageStr += srd.ReadToEnd();
stream.Close();
srd.Close();
}
catch (Exception e)
{
PageStr += e.Message;
}
return PageStr;
}
復制代碼 代碼如下:
public string WebClientGet(string url)
{
var client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
var stream = client.OpenRead(url);
if (stream == null) return "";
var reader = new StreamReader(stream, Encoding.Default);
var result = reader.ReadToEnd();
stream.Close();
reader.Close();
return result;
}
“HttpRequest Get和Post怎么調用其他頁面”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。