ga('set', 'anonymizeIp', 1);
開發時總會需要用到線上功能,這時候就需要使用http request來收發資訊。
本文講述如何在C#中操作連線問題,並且做訊息收發(GET,POST)。
string targetUrl = "http://localhost:8080/Request/getTest?value=1";
HttpWebRequest request = HttpWebRequest.Create(targetUrl) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 3000;
string result = "";
// 取得回應資料
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
Response.Write(result);
上方是利用GET方法向伺服器發送request,
其中target URL部分可依照使用者不同ip, port去做修改,也可做成動態string。
另外後方帶的API URL也可依照server API設計去做不同參數傳遞。
再來使用StreamReader將server回傳的資料讀出,並存入想要的參數中。
string targetUrl = "http://localhost:8080/Request/postTest";
string para = "p=Arvin";
byte[] postData = Encoding.UTF8.GetBytes(para);
HttpWebRequest request = HttpWebRequest.Create(targetUrl) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 3000;
request.ContentLength = postData.Length;
// 寫入 Post Body Message 資料流
using (Stream st = request.GetRequestStream())
{
st.Write(postData, 0, postData.Length);
}
string result = "";
// 取得回應資料
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
Response.Write(result);
與GET最大的不同是POST在request的同時會將資料傳遞至server上的目標API,server再針對傳入的資料做解析後,傳回相應的回應資料。
string targetUrl = "http://localhost:8080/Request/postReTest";
string para = "url=http://localhost:8080/Request/default";
byte[] postData = Encoding.UTF8.GetBytes(HttpUtility.HtmlEncode(para));
HttpWebRequest request = HttpWebRequest.Create(targetUrl) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 3000;
request.ContentLength = postData.Length;
request.AllowAutoRedirect = false; // 禁止重新導向網頁
// 寫入 Post Body Message 資料流
using (Stream st = request.GetRequestStream())
{
st.Write(postData, 0, postData.Length);
}
string result = "";
// 取得回應資料
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.Found) // 判斷是否為 302
{
// 取得返回的Header中的Location參數,Location函有重新導向的網址資訊
Uri redirectUrl = new Uri(response.Headers["Location"]);
// 利用HttpUtility類別的ParseQueryString方法剖析QueryString參數
result = HttpUtility.ParseQueryString(redirectUrl.Query, Encoding.UTF8).Get("para");
}
}
Response.Write(result);
首先為了避免被重新導向,所以要增加 request.AllowAutoRedirect = false 設定,當Server有重新導向動作時,response回來的StatusCode應該為302,302 有包含導向的Location,所以要取得 response 回來的 Header 資料中的 Location ,Location 將包含導向的URL位置及參數,最後利用HttpUtility類別的ParseQueryString方法剖析QueryString中要取得的參數即可。